Control Two LED's with one button

I am having a hard time finding an example on how to control two LED's with one button.

What I would like to do is turn one LED on with a button press and then on the second button press turn the first LED off and turn the second LED on.

I am thinking that I need to a create a variable that increments each time the button is pressed. Push button once var = 1 turns LED 1 on. Button press second time var = 2 turns LED1 off and LED2 on then resets var back to 0. Seems overly complicated though and I want to minimize the code as much as possible.

Any guidance would be greatly appreciated.

Have a look at the statechangedetection example that comes with the Arduino software. With a few little changes this can be done very easily.

got pretty bored so I made this
it compiles fine on my machine so if you have any errors I will fix them

int switchPin = 2;              // switch is connected to pin 2
    int led1Pin = 8;
    int led2pin = 9;

    int val;                        // variable for reading the pin status
    int val2;                       // variable for reading the delayed status
    int buttonState;                // variable to hold the button state
    int Mode = 0;              // What mode is the light in?

    void setup() {
      pinMode(switchPin, INPUT);    // Set the switch pin as input
      pinMode(led1Pin, OUTPUT);
      pinMode(led2pin, OUTPUT);
      buttonState = digitalRead(switchPin);   // read the initial state
    }

    void loop(){
      val = digitalRead(switchPin);      // read input value and store it in val
      delay(10);                         // 10 milliseconds is a good amount of time
      val2 = digitalRead(switchPin);     // read the input again to check for bounces
      if (val == val2) {                 // make sure we got 2 consistant readings!
        if (val != buttonState) {          // the button state has changed!
          if (val == LOW) {                // check if the button is pressed
            if (Mode == 0) {          
              Mode = 1;               
            } else {
                if (Mode == 1) {        
                Mode = 2;           
            } else {
                if (Mode == 2) {      
                Mode = 3;           
            } else {
                if (Mode == 3) { 
                Mode = 0;          
                  }
            }
           }
          }
         }
        }
        buttonState = val;                 // save the new state in our variable
      }

      // Now do whatever the lightMode indicates
      if (Mode == 0) { // all-off
        digitalWrite(led1Pin, LOW);
        digitalWrite(led2pin, LOW);
      }

      if (Mode == 1) { 
        digitalWrite(led1Pin, HIGH);
        digitalWrite(led2pin, LOW);
      }

      if (Mode == 2) { 
        digitalWrite(led1Pin, LOW);
        digitalWrite(led2pin, HIGH);
      }
      if (Mode == 3)  { 
        digitalWrite(led1Pin, HIGH);
        digitalWrite(led2pin, HIGH);
      }    
    }

Cheers :slight_smile:

1 Like

Thank you that was very useful

Seems overly complicated though and I want to minimize the code as much as possible.

How about this:

led1 = (button pressed & (led1 is on))? off:on;
led2 = (led1 is on)? off:on;

const int buttonPin = 3;    // pin to read button
const int oddLED = 9;       // LED lit on odd button presses
const int evenLED = 10;     // LED lit on even button presses

int pressCnt = 0;           // total # of button presses

void setup()
{

  pinMode(buttonPin, INPUT);

}

void loop()
{
  // if button is pressed
  if( digitalRead(buttonPin) ) {
    
    // increment count
    pressCnt++;
    
    // turn on even or odd LED
    digitalWrite(oddLED, pressCnt % 2);
    digitalWrite(evenLED, !(pressCnt % 2));
    
    // debounce
    delay(200);
  }


}

@BlueEyes:
What does that code do if the switch is held down. It does not do what OP asked for.

How is the switch supposed to be wired to use that code? Posting code that works with hardware, but not describing how to connect the hardware does the newbie poster little good.

Looks like I got bored too :slight_smile:

int switchPin = 2;              // switch is connected to pin 2
int led1Pin = 8;
int led2pin = 9;

int val;                        // variable for reading the pin status
int val2;                       // variable for reading the delayed status
int buttonState;                // variable to hold the button state
int Mode = 0;              // What mode is the light in?
boolean modeChanged = false;
const int NUM_MODES = 4;


void setup() {
    pinMode(switchPin, INPUT);    // Set the switch pin as input
    pinMode(led1Pin, OUTPUT);
    pinMode(led2pin, OUTPUT);
    buttonState = digitalRead(switchPin);   // read the initial state
}


void loop(){
    val = digitalRead(switchPin);      // read input value and store it in val
    delay(10);                         // 10 milliseconds is a good amount of time
    val2 = digitalRead(switchPin);     // read the input again to check for bounces
    if (val == val2) {                 // make sure we got 2 consistant readings!
        if (val != buttonState) {          // the button state has changed!
            if (val == LOW) {                // check if the button is pressed
                Mode++;
                if (Mode >= NUM_MODES) {
                    Mode = 0;
                }
                modeChanged = true;
            }
        }
        buttonState = val;                 // save the new state in our variable
    }

    if (modeChanged) {
        modeChanged = false;

        // Now do whatever the lightMode indicates
        switch(Mode) {
        case 0:
            digitalWrite(led1Pin, LOW);
            digitalWrite(led2pin, LOW);
            break;

        case 1:
            digitalWrite(led1Pin, HIGH);
            digitalWrite(led2pin, LOW);
            break;

        case 2:
            digitalWrite(led1Pin, LOW);
            digitalWrite(led2pin, HIGH);

        case 3:
            digitalWrite(led1Pin, HIGH);
            digitalWrite(led2pin, HIGH);
        }
    }
}

(warning: compiled but untested code, use at your own risk :stuck_out_tongue_winking_eye: )

@PaulS:

The OP said

What I would like to do is turn one LED on with a button press and then on the second button press turn the first LED off and turn the second LED on.

and that's what the code does. If the OP wants to handle the case where someone holds the button down then they could replace the "if" statement with a "while" statement.

I thought that the code was documented enough to show how it was wired, but I'll explain how I set it up on a breadboard. A momentary button was connected on one side to 5V and the other to ground through a 10K pull-down resistor and to Arduino digital pin 3 ("buttonPin") through a 100 Ohm resistor. Two LEDs were connected to ground via 330 Ohm resistors and their anodes were connected to Arduino digital pins 9 and 10 ("oddLED" and "evenLED").

When the sketch runs neither LED is lit. When the button is clicked the LED connected to Arduino digital pin 9 ("oddLED") lights. When the button is clicked again the lit LED turns off and the LED connected to Arduino digital pin 10 ("evenLED") lights.

and that's what the code does.

No, it doesn't. It changes the pressCnt variable more than once if the switch is held down. The value will be incremented every 200 milliseconds (plus a little bit) for as long as the switch is held down.

OP was looking for something that incremented the value only once each time the switch was pressed. That requires keeping track of the previous state of the pin, so that the transitions can be detected.

Well, YOU'RE defining a button press as someone holding the button down. I'M defining a button press as someone pressing the button and then letting it up, holding it down counts as multiple button presses. I guess it's up to the OP to define what a button press is. What's wrong with that? It's example code, the OP can handle extreme cases anyway they want.

I'M defining a button press as someone pressing the button and then letting it up

Assuming that they release it withing 200 milliseconds.

Good Morning,

I was assuming a button press just that. Pressed and then let up. Is there a way to make it so that if the button is help down for an unspecified amount of time and then let up, it only counts as one button press?

Thank you for all of your assistance with this.

Is there a way to make it so that if the button is help down for an unspecified amount of time and then let up, it only counts as one button press?

The pin state will read one way while the switch is pressed, and the other way when it is released.

By keeping track of the state from the last iteration of loop, you can tell when the transitions (to pressed or to released) occur. When you have detected a transition, the current state of the switch (pressed or released) defines which transition occurred.

So I'm new to the Arduino programming language and could use some pointers. I'm trying to do the same type of thing the OP asked about but want to add more switches/options, i.e. having one switch turn on/off three LEDs and another switch turn on/off the LEDs in sequence. I was able to follow That1Guy99's program but can't get the second switch to work.
Here's my code so far:

const int buttonPinA = 2;
const int buttonPinB = 3;
const int ledPinA = 11;
const int ledPinB = 10;
const int ledPinC = 9;

int val;
int val2;
int buttonStateA = 0;
int buttonStateB = 0;
int Mode = 0;

void setup() {

pinMode(ledPinA, OUTPUT);
pinMode(ledPinB, OUTPUT);
pinMode(ledPinC, OUTPUT);

pinMode(buttonPinA, INPUT);
pinMode(buttonPinB, INPUT);
buttonStateA = digitalRead(buttonPinA);
buttonStateB = digitalRead(buttonPinB);
}

void loop(){

val = digitalRead(buttonPinA);
delay(10);
val2 = digitalRead(buttonPinA);
if (val == val2) {
if (val !=buttonStateA) {
if (val == LOW) {
if (Mode == 0) {
Mode = 1;
}else {
if (Mode == 1) {
Mode = 0;
}
}
}
}
buttonStateA = val;
}

val = digitalRead(buttonPinB);
delay(10);
val2 = digitalRead(buttonPinB);
if (val == val2) {
if (val !=buttonStateB) {
if (val == LOW) {
if (Mode == 2) {
Mode = 3;
}else {
if (Mode == 3) {
Mode = 4;
}else {
if (Mode == 4) {
Mode = 2;
}
}
}
}
}
buttonStateB = val;
}
if (Mode == 1) {
// turn LED on:
digitalWrite(ledPinA, HIGH);
digitalWrite(ledPinB, HIGH);
digitalWrite(ledPinC, HIGH);
}
if (Mode == 0) {
// turn LED off:
digitalWrite(ledPinA, LOW);
digitalWrite(ledPinB, LOW);
digitalWrite(ledPinC, LOW);
}
if (Mode == 2) {
digitalWrite(ledPinA, HIGH);
digitalWrite(ledPinB, LOW);
digitalWrite(ledPinC, LOW);
}
if (Mode == 3) {
digitalWrite(ledPinA, LOW);
digitalWrite(ledPinB, HIGH);
digitalWrite(ledPinC, LOW);
}
if (Mode == 4) {
digitalWrite(ledPinA, LOW);
digitalWrite(ledPinB, LOW);
digitalWrite(ledPinC, HIGH);
}
}

Any help would be great!
Thx,
D

fascistempire:
So I'm new to the Arduino programming language and could use some pointers.

Welcome.
There is no "Arduino programming language", it's just C++.
Please use code tags when posting code.

I really dislike dealing with buttons, it clutters up the code and makes it harder to see what I'm "really" trying to do. So I wrote a library to simplify things. This should do what the OP wanted, if I understand correctly.

#include <Button.h>              //https://github.com/JChristensen/Button

const int BUTTON_PIN = 2;        //wire the button from the pin to ground
const boolean PULLUP = true;     //use the internal pullup resistor
const boolean INVERT = true;     //using a pullup means normal (unpressed) state is high
const unsigned long DEBOUNCE_MS = 25;    //button debounce time in milliseconds
const int LED1_PIN = 3;          //wire the LEDs from the pin to ground,
const int LED2_PIN = 4;          //  through an appropriate current-limiting resistor

Button myBtn(BUTTON_PIN, PULLUP, INVERT, DEBOUNCE_MS);    //define the button

void setup(void)
{
    pinMode(LED1_PIN, OUTPUT);
    pinMode(LED2_PIN, OUTPUT);
}

void loop(void)
{
    static boolean ledState;

    myBtn.read();                   //Read the button

    if (myBtn.wasPressed()) {       //If the button was pressed, change the LED state
        ledState = !ledState;
        digitalWrite(LED1_PIN, ledState);
        digitalWrite(LED2_PIN, !ledState);
    }
}

Thy not make it as simple as this :

Initial states : Led 1 - On ; Led2- Off
On pushing button : change the states. ( i.e., Off is on and on is off )