I have an Arduino Mega 2560 and I'm using a momentary push-to-make switch and an LED.
From when the system is powered on, I want it to wait until the switch is pushed.
It should then switch the LED on, set the 'pwrStatus' variable to 1.
if pressed a second time, I'd like it to 'know' that the pwrStatus variable was 1, therefore the process is running and it must instead switch the LED off and stop the process.
I've tried to get this working using an Interrupt, but I think my problem is that it loops through the whole thing so fast, sometimes the length of the switch press means that it's evaluating whether the switch is open or closed at that exact moment, so it's unreliable.
Is there a way I can kind of 'isolate' it so that once the switch is pressed it stops looping until the switch has been released and it's finished the remaining function call(s)?
in my code sample below, the push switch is on pin 19 and the power LED is on pin 30. I'm using a resistor to pull the switch input down when not pressed.
Thank you for any help
const int interruptPin = 19;
int pwrStatus = 0;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(30, OUTPUT); //button power led
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(19), btnFunction, RISING);
}
// the loop function runs over and over again forever
void loop() {
}
void btnFunction() {
if (pwrStatus == 0) {
digitalWrite(30, HIGH);
pwrStatus = 1;
} else if (pwrStatus == 1) {
digitalWrite(30, LOW);
pwrStatus = 0;
}
}
A couple of things.
First, you don't need to have a pull down resistor if you enable the pull up resistor on your pin. just tied it to ground.
Second, in your interrupt, it is best to just set a flag that it occurred and deal with it within your loop(). You then reset that variable.
Also look at debouncing your button.