简体   繁体   中英

Why do I have to execute my button function twice in order for my logic to work properly?

I'm writing a simple alarm program that uses a PIR motion sensor that detects an intrusion.

My expected logic is trying to make toggle button for my sensor to be turn on or off. By default the sensor should be inactive/turned off, unless the first click is clicked then in that case the sensor would be active.

Here's the code

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();

    }


}

Actual outcome is: Sensor is active by default. First click, still active. Second Click, still active. Third click, inactive and the subsequent clicks works as it should be (on and off).

Any idea what's going on? I've been trying to figure this out for hours

Either set

static bool onOff = true;

if you want your sensor active in the beginning.

or in Main():

motionSensor.DisableInterrupt();

if you want your senseor inactive in the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM