0

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);
 }
} 
Rohit Gupta
6162 gold badges5 silver badges18 bronze badges
asked Feb 26 at 15:22
1
  • you have an inconsistency in your thinking ... you set the state of two LEDs in the first part of the if block, but then you set the state of only one LED in the second part of the if block Commented Feb 26 at 16:13

1 Answer 1

0

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.

answered Feb 26 at 16:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.