toggle between two LEDs with one push (momentary) button

Hello All,

I'm working on a project with what i thought was the simple goal of using a momentary push button to switch between two LEDs. Once the button is pushed, the intention is to light one LED for about 2 seconds (the delay time isn't too important). The next time the button is pushed, I'd like the other LED to light for same time. It seemed simple in concept but I'm having trouble working it out. I suspect I need to keep track of the last LED that was lit, and then flip to the other one on the next button push but I've taken several stabs at it now and can't seem to finish the code so that it works. Of course I'm relatively new to Arduino and programming.

Thank you for any help you can provide.



int LED1=6;        // LED1 tied to pin 6
int LED2=7;        // LED2 tied to pin 7
int buttonRead;    // variable to hold value of button
int buttonPin=2;   // button tied to pin 2
int dt=20;         // delay next button read - debounce
int delayoff=2000; // once button is pushed, keep LED lit delay
int laststate=1;   // variable to keep last LED lit (1 or 2)

void setup() {
  // put your setup code here, to run once:
pinMode(LED1, OUTPUT);         // set LED1 pin to OUTPUT
pinMode(LED2, OUTPUT);         // set LED2 pin to OUTPUT

pinMode(buttonPin,INPUT);      // set buttonPin to INPUT
digitalWrite(buttonPin, HIGH); // set buttonPin HIGH for pull-up resistor
                               // -- button state will always be 1
                               // -- until button is pressed and then
                               // -- will read 0
Serial.begin(9600);            // begin serial monitor for debug


void loop() {
  // put your main code here, to run repeatedly:


if (buttonRead==0 && laststate==1) {
  digitalWrite(LED1, HIGH);
  digitalWrite(LED1, LOW);

if (buttonRead=0 && laststate==2) {
  digitalWrite(LED2, HIGH);
  digitalWrite(LED2, LOW);



The most obvious problem is that you are not updating laststate in the sketch

I had some additional code in there, several times, and I cleared it out because I wanted a "cleaner slate" for folks to work with when trying to lead me in the right direction. Guess that was a bad idea. My intuition isn't the best, obviously. Working through these things can be a humbling experience. I know everyone's time is valuable. Sorry for the omission.



Have you looked at the StateChangeDetection example in the IDE. With a little adaptation it will do what you want

You can use counter. See one button for multiple functions