第二次运行时清除代码 [英] Clear code the second time it runs
本文介绍了第二次运行时清除代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将我用于控制覆盆子的GPIO的这部分代码用白色。
当我点击开始按钮然后停止按钮时,继电器正常工作。当我第二次这样做时,我得到一个错误。我做错了什么...
Whit this part of my code I use to control the GPIO of a raspberry.
When I click on the start button and then the stop button the relay is working properly. When I do this for the second time i get an error. What am I doing wrong...
{
private const int relay1 = 4;
private const int relay2 = 25;
private const int relay3 = 22;
private const int relay4 = 5;
private GpioPin pin;
private GpioPinValue pinValue;
public MainPage()
{
//Scherm laden
InitializeComponent();
}
//Relay1 START
private void StartR1_Click(object sender, RoutedEventArgs e)
{
var gpio = GpioController.GetDefault();
pin = gpio.OpenPin(relay1);
pinValue = GpioPinValue.High;
pin.Write(pinValue);
pin.SetDriveMode(GpioPinDriveMode.Output);
//Button Control Aan/Uit
StartR1.IsEnabled = false;
StopR1.IsEnabled = true;
}
//Relay1 STOP
private void StopR1_Click(object sender, RoutedEventArgs e)
{
var gpio = GpioController.GetDefault();
pinValue = GpioPinValue.Low;
pin.Write(pinValue);
pin.SetDriveMode(GpioPinDriveMode.Input);
//Button Control Aan/Uit
StartR1.IsEnabled = true;
StopR1.IsEnabled = false;
}
推荐答案
狂猜:第二次,调用openPin
方法失败,因为该引脚已在独占模式下打开(请参阅文档 [ ^ ])。
如果是那么你应该只进行一次这样的调用(可能是你的应用程序启动时)。
Wild guess: the second time, the call to theopenPin
method fails because the pin is already open in exclusive mode (see the documentation[^]).
If that is the case then you should make such call just one time (possibly at your application startup).
看这里: https://ms-iot.github.io/content/en-US/win10/samples/PinMappingsRPi2.htm [
打开的针脚是处置 [ ^ ](用using子句包装)。
你不能简单地重新打开它。正确使用IDisposable模式。
Look here: https://ms-iot.github.io/content/en-US/win10/samples/PinMappingsRPi2.htm[^]
The pin opened is disposed[^] (wrapped in using clause).
You can't simply reopen it. Use the IDisposable pattern properly.
CPallini和Zoltan的解决方案是正确的。更具体地说,您需要执行以下操作:
CPallini's and Zoltan's solutions are correct. More specifically, you need to do the following:
var gpio = GpioController.GetDefault();
if (pin == null) // add this line.
pin = gpio.OpenPin(relay1);
祝你好运!
Good luck!
这篇关于第二次运行时清除代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文