晚上好,
我正在对家庭自动化系统的开始进行一些故障排除。我正在尝试在 C# 中使用 Raspberry PI 3 和 Windows IOT 切换继电器。我一直在玩代码,我可以看到继电器切换一两次,但随后应用程序崩溃了。我是 IOT 菜鸟,所以这段代码有什么问题吗?(变量名是在别处定义的,我下面的奇怪变量名是为我的 WIP 项目...我更喜欢用英语进行故障排除)...
private void BtnTempFan_Click(object sender, RoutedEventArgs e)
{
if (BtnTempFan.IsChecked == true)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.High);
}
else
{
TempFan.Dispose();
}
}
private void TogglePin(GpioPin PinName, int PinNumber, ToggleButton Name, GpioPinValue value)
{
int pinnumber = PinNumber;
GpioPinValue pinvalue;
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
if (gpio == null)
{
PinName = null;
LblError.Text = "We can't find the controller on the device" + PinName;
LblError.Visibility = Visibility.Visible;
return;
}
if (PinName == null)
{
LblError.Text = "We can't find the pin on the device. Pin number " + PinNumber + "does not exist";
LblError.Visibility = Visibility.Visible;
return;
}
if (Name.IsChecked == true)
{
pinvalue = value;
PinName.Write(pinvalue);
PinName.SetDriveMode(GpioPinDriveMode.Output);
}
你没有说例外是什么。但是,我相信您应该每个应用程序只打开一次 GPIO 引脚:
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
您可以在每次单击按钮时调用一次的方法中使用它。通过多次打开 pin,您会遇到 pin 已经打开,我相信这就是引发异常并使应用程序崩溃的原因。
在我的代码中,我在“驱动程序”类中处理引脚状态,并Connect
在启动应用程序时调用了一个方法。例如:
public async Task Connect()
{
var gpioController = await GpioController.GetDefaultAsync();
try
{
_openPin = gpioController.OpenPin(_doorMotorOpenPin);
_closePin = gpioController.OpenPin(_doorMotorClosePin);
}
}
这封装了 2 个引脚:_openPin
并封装_closePin
到一个我可以管理其生命周期的类中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句