如何在后台任务中从gpio读取值?当我使用BackgroundApp(IoT)模板时,C#Win IOT RP3
问题描述:
我从引脚没有得到任何值。 我在前台应用程序中尝试它,但按按钮时没有触发事件。 有人能告诉我我做错了什么吗?如何在后台任务中从gpio读取值?当我使用BackgroundApp(IoT)模板时,C#Win IOT RP3
这里是我的代码
namespace BackgroundApplication2
{
public sealed class StartupTask : IBackgroundTask
{
private const int LED_PIN = 6;
private const int BUTTON_PIN = 5;
private GpioPin ledPin;
private GpioPin buttonPin;
private GpioPinValue ledPinValue = GpioPinValue.High;
public void Run(IBackgroundTaskInstance taskInstance)
{
InitGPIO();
}
private void InitGPIO()
{
var gpio = GpioController.GetDefault();
if (gpio == null)
{
Debug.WriteLine("There is no GPIO controller on this device.");
return;
}
buttonPin = gpio.OpenPin(BUTTON_PIN);
ledPin = gpio.OpenPin(LED_PIN);
ledPin.Write(GpioPinValue.High);
ledPin.SetDriveMode(GpioPinDriveMode.Output);
if (buttonPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp))
buttonPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
else
buttonPin.SetDriveMode(GpioPinDriveMode.Input);
buttonPin.DebounceTimeout = TimeSpan.FromMilliseconds(50);
buttonPin.ValueChanged += buttonPin_ValueChanged;
Debug.WriteLine("GPIO pins initialized correctly.");
}
private void buttonPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
{
if (e.Edge == GpioPinEdge.FallingEdge)
{
ledPinValue = (ledPinValue == GpioPinValue.Low) ?
GpioPinValue.High : GpioPinValue.Low;
ledPin.Write(ledPinValue);
}
}
}
}
本规范是由于您的BackgroundApp执行InitGPIO()
功能后退出工作正常,在UWP-应用
答
此问题。所以你不能接收任何事件。
你需要调用“GetDeferral”方法来阻止应用程序退出。你可以这样做:
public void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
InitGPIO();
}
有关此行为的更多信息,可以参考here。