I have an task for my class where we have to make 2 LEDS blink alternatively using a pushbutton. I've figured out how to do the blinking and alternating but from time to time one of the led would go twice in a row instead of the other led blinking. Need help figuring out what's making it do this in my code. I'm using Tinkercad with Arduino UNO.
int buttonPin = 7;
int redledpin = 11;
int orangeledpin = 12;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
}
void loop ()
{
if(digitalRead(buttonPin) == HIGH) {
digitalWrite(11, LOW);
digitalWrite(12, LOW);
}
else {
digitalWrite(11, HIGH);
delay(500);
digitalWrite(11, LOW);
delay(500);
}
if(digitalRead(buttonPin) == HIGH) {
digitalWrite(11, LOW);
digitalWrite(12, LOW);
}
else {
digitalWrite(12, HIGH);
delay(500);
digitalWrite(12, LOW);
delay(500);
}
if(digitalRead(buttonPin) == HIGH) {
digitalWrite(11, LOW);
digitalWrite(12, LOW);
}
}
1 Answer 1
Your behavior depends solely on the timing of your button presses. I'm assuming that buttonPin is LOW when pressed, therefore when you press the button you will trigger an if statement to evaluate to false - but which one? It all depends on which instruction the main loop happens to be executing when the button is pressed, which explains why sometimes your behavior works and sometimes doesn't.
There's a bunch of routes you can take here. A simple one would be two while loops (in sequence, not nested), each one waiting for buttonPin to go low. Both while loops keep the LED pins low, then you blink LED 1 after the first while loop ends and blink LED 2 after the second one ends.
Another simple solution is to make a new variable that corresponds to the most recently blinked LED. Whenever a button is pressed, check the variable - if its 0, blink LED 1 and set the variable to 1, and if its 1, blink LED 2 and set the variable to 0.
if
block, but then you set the state of only one LED in the second part of theif
block