为什么我必须执行两次按钮功能才能使我的逻辑正常工作

本文关键字:工作 我的 常工作 按钮 执行 为什么 两次 功能 | 更新日期: 2023-09-27 18:37:10

我正在编写一个简单的警报程序,该程序使用检测入侵的 PIR 运动传感器。

我预期的逻辑是尝试打开或关闭传感器的切换按钮。 默认情况下,传感器应处于非活动状态/关闭状态,除非单击第一次单击,在这种情况下,传感器将处于活动状态。

这是代码

public class Program
{
    static InterruptPort motionSensor = new InterruptPort(Pins.GPIO_PIN_D0, false, ResistorModes.Disabled, InterruptModes.InterruptEdgeLow);
    static OutputPort redLED = new OutputPort(Pins.GPIO_PIN_D9, false);
    static OutputPort greenLED = new OutputPort(Pins.GPIO_PIN_D6, false);
    static OutputPort blueLED = new OutputPort(Pins.GPIO_PIN_D5, false);
    static InterruptPort onboardBtn = new InterruptPort(Pins.ONBOARD_BTN, false, Port.ResistorMode.Disabled, InterruptModes.InterruptEdgeLow);
    static bool onOff;
    public static void Main()
    {
        onboardBtn.OnInterrupt += new NativeEventHandler(onboardBtn_onInterrupt);
        motionSensor.OnInterrupt += new NativeEventHandler(motion_onInterrupt);
        while (true)
        {
            Thread.Sleep(Timeout.Infinite);
        }
    }
    static void onboardBtn_onInterrupt(UInt32 data1, UInt32 data2, DateTime Timeout)
    {
        onboardBtn.DisableInterrupt();
        //Motion Sensor
        if (onOff == false)
        {
            motionSensor.DisableInterrupt();
            onOff = true;
        }
        else
        {
            motionSensor.EnableInterrupt();
            onOff = false;
        }
        onboardBtn.EnableInterrupt();
    }
    static void motion_onInterrupt(uint data1, uint data2, DateTime time)
    {
        motionSensor.DisableInterrupt();
        Debug.Print("Movement found ");
        int i = 0;
        while (i < 5)
        {
            blueLED.Write(true);
            Thread.Sleep(100);
            blueLED.Write(false);
            Thread.Sleep(50); 
            redLED.Write(true);
            Thread.Sleep(100);
            redLED.Write(false); 
            Thread.Sleep(50);
            i++;
        }
        motionSensor.EnableInterrupt();
    }

}

实际结果为:默认情况下,传感器处于活动状态。 第一次点击,仍然处于活动状态。第二次点击,仍然有效。 第三次点击,处于非活动状态,随后的点击按预期工作(打开和关闭)。

知道发生了什么吗? 几个小时以来,我一直在试图弄清楚这一点

为什么我必须执行两次按钮功能才能使我的逻辑正常工作

任一集合

static bool onOff = true;

如果您希望传感器在开始时处于活动状态。

或在主():

motionSensor.DisableInterrupt();

如果你想让你的感觉在开始时不活跃。