Win10 IoT 8 GPIO输入输出

微软官方的例子Blinky能够控制GPIO的输出并在界面中显示出来,通过我自己的改造,将这个工程从GPIO输入来控制输入LED的状态并且在界面中显示出来,而输入是通过GPIO的事件触发来完成,并立即刷新界面显示。

在winform中只要用Invoke即可实现跨线程访问UI,但是在这个UWP工程里的界面元素没有Invoke方法,通过叶帆老师的帮助采用C#5.0的新特性async await异步方法解决了跨线程访问UI的功能。

部分代码如下:

    public sealed partial class MainPage : Page
    {
        private const int LED_PIN = 5;
        private const int SWITCH_PIN = 6;
        private GpioPin pinled;
        private GpioPin pinswitch;
        private SolidColorBrush redBrush = new SolidColorBrush(Windows.UI.Colors.Red);
        private SolidColorBrush grayBrush = new SolidColorBrush(Windows.UI.Colors.LightGray);

        public MainPage()
        {
            this.InitializeComponent();
            InitGPIO();
        }

        private void InitGPIO()
        {
            var gpio = GpioController.GetDefault();

            // Show an error if there is no GPIO controller
            if (gpio == null)
            {
                pinled = null;
                pinswitch = null;
                GpioStatus.Text = "There is no GPIO controller on this device.";
                return;
            }
            pinswitch = gpio.OpenPin(SWITCH_PIN);
            pinswitch.DebounceTimeout = new TimeSpan(0, 0, 0, 0, 50);//消抖时间
            pinswitch.SetDriveMode(GpioPinDriveMode.Input);
            pinled = gpio.OpenPin(LED_PIN);
            pinled.SetDriveMode(GpioPinDriveMode.Output);
            pinled.Write(pinswitch.Read());
            pinswitch.ValueChanged += Pinswitch_ValueChanged;

            GpioStatus.Text = "GPIO pin initialized correctly.";
        }

        private async void Pinswitch_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
        {
            GpioPinValue pinvalue = pinswitch.Read();
            pinled.Write(pinvalue);

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                switch (pinvalue)
                {
                    case GpioPinValue.Low:
                        LED.Fill = redBrush;
                        break;
                    case GpioPinValue.High:
                        LED.Fill = grayBrush;
                        break;
                    default:
                        break;
                }
            });
        }
    }

  

 

完整程序包连接如下:

 http://download.csdn.net/detail/wangji666666/9411014

注意:要将项目属性页“Debug”下的Remote machine中内容改成自己的win10iot设备的名称或者是IP

posted @ 2016-01-20 10:29  wj66  阅读(2236)  评论(0编辑  收藏  举报