ValueChanged not firing with C# Win10 Iot

◇◆丶佛笑我妖孽 提交于 2019-12-02 17:41:42

问题


It seems exactly like Win10 IoT - RaspBerry Pi2: ValueChanged not called when GPIO change I have a raspberry pi 2 with win10 IoT (creator version) and have this C# code:

public sealed class StartupTask : IBackgroundTask
{
    private const int SENSOR_PIN = 17;
    private GpioPin pinSensor;

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        taskInstance.Canceled += TaskInstance_Canceled; // "destructor"

        var gpio = GpioController.GetDefault();

        if (gpio != null)
        {
            pinSensor = gpio.OpenPin(SENSOR_PIN); // also tried with GpioSharingMode.SharedReadOnly

            var r = pinSensor.Read(); // works and changes if sensor changes. Verified with quickwatch

            pinSensor.SetDriveMode(GpioPinDriveMode.Input);
            pinSensor.DebounceTimeout = TimeSpan.FromMilliseconds(20);

            pinSensor.ValueChanged += PinIn_ValueChanged;
        }
    }

    private void PinIn_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
    {
        // never gets hit... 
    }

    private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        pinSensor.Dispose();
    }
}

led on sensor and quickwatch say the GpioPinValue does alternate between high and low... so should get hit...

When I retrieve the drive mode after setting it to input. It tells me it actually is set to input:

var dm = pinSensor.GetDriveMode();

as was suggested in the comment of the linked stack overflow issue. So what am I doing wrong? And more important: why?


回答1:


When the Run method ends, unless a deferral object is created, the Background Application ends. The common practice, for asynchronous programming is to take a deferral like this:

var deferval = taskInstance.GetDeferral();

Ref:Developing Background Applications



来源:https://stackoverflow.com/questions/43763366/valuechanged-not-firing-with-c-sharp-win10-iot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!