2 Buttons and 2 LED Help.

Hi. I am really new to arduino and posting in this forum so please be easy on me.

My concept is if button #1 is pressed, led #1 should light up and if button #2 is pressed, led #2 should light up. Its like choosing an answer where if you pressed button #1, led #1 should light up and led #2 should not, meaning only one led will light up depending on what button was pressed. I really thought that it would be easy since the idea is similar to a radio button when making a form.

My code is just a modified from the debounce example since I need the led to be lit up until the other button is pressed. So I tried to duplicate almost all of the variables. I don't know if I'm doing it correctly.

I actually don't know if debounce actually works in the code because honestly, its the first time I encountered "debounce". I have minimal experience or knowledge on arduino, and by 'minimal', I mean I only have knowledge on blinking led.

//Multiple Choice with 2 buttons and 2 pins

const int buttonPin = 13;
const int buttonPin2 = 12;    // the number of the pushbutton pin
const int ledPin = 11;       // the number of the LED pin
const int ledPin2 = 10;  

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int ledState2 = HIGH;
int buttonState;             // the current reading from the input pin
int buttonState2;             // the current reading from the input pin
int lastButtonState = LOW;
int lastButtonState2 = LOW;   // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers


void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);
  int reading2 = digitalRead(buttonPin2);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed: [[DIri ako mag-utro]]
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH [[o diri?]]
      if (buttonState == HIGH) {

        if (ledState == LOW)
        {
          digitalWrite(ledState,HIGH);
          digitalWrite(ledState2,LOW);
          ledState = LOW;
          ledstate2 = HIGH;
        }
      }
    }
    lastButtonState = reading;
    if (reading2 != buttonState) {
      buttonState2 = reading2;

      // only toggle the LED if the new button state is HIGH [[o diri?]]
      if (buttonState2 == HIGH) {
       
        if (ledState2 == HIGH)
        {
          digitalWrite(ledState,LOW);
          digitalWrite(ledState2,HIGH);
          ledState = HIGH;
          ledstate2 = LOW;
        }
      }
    }
  }

  if (buttonState2 && buttonState == HIGH)
  {
  }

  // save the reading. Next time through the loop, it'll be the lastButtonState:
  lastButtonState = reading;
  lastButtonState2 = reading2;
}
//END

My plan for this project is that once I get this running, I will add one more button and led until I can make a project involving many buttons and pins where led #4 will light up if button #4 is pressed.

Thank you in advance for looking into my problem.

OK, so it is "radio-buttons" you want?

Or toggle?

"Radio-buttons" do not strictly need de-bounce since it does not matter how many times you press the button.

Toggle will not work without de-bounce.

Buttons should wire to ground, Either you use INPUT_PULLUP or you provide a pull-up.

// Radio Buttons!
const int led1Pin =  3;    // LED pin number
const int button1 =  2;
const int led2Pin =  5; 
const int button2 =  4;
const int led3Pin =  6;
const int button3 =  7;
const int led4Pin =  9;
const int button4 =  8;
char bstate1 = 0;
char bstate2 = 0;
char bstate3 = 0;
char bstate4 = 0;
unsigned long bcount1 = 0; // button debounce timer.  Replicate as necessary.
unsigned long bcount2 = 0;
unsigned long bcount3 = 0;
unsigned long bcount4 = 0;


// Have we completed the specified interval since last confirmed event?
// "marker" chooses which counter to check
// Routines by Paul__B of Arduino Forum
boolean timeout(unsigned long *marker, unsigned long interval) {
  if (millis() - *marker >= interval) { 
    *marker += interval;    // move on ready for next interval
    return true;       
  } 
  else return false;
}

// Deal with a button read; true if button pressed and debounced is a new event
// Uses reading of button input, debounce store, state store and debounce interval.
// Routines by Paul__B of Arduino Forum
boolean butndown(char button, unsigned long *marker, char *butnstate, unsigned long interval) {
  switch (*butnstate) {               // Odd states if was pressed, >= 2 if debounce in progress
  case 0: // Button up so far, 
    if (button == HIGH) return false; // Nothing happening!
    else { 
      *butnstate = 2;                 // record that is now pressed
      *marker = millis();             // note when was pressed
      return false;                   // and move on
    }

  case 1: // Button down so far, 
    if (button == LOW) return false; // Nothing happening!
    else { 
      *butnstate = 3;                 // record that is now released
      *marker = millis();             // note when was released
      return false;                   // and move on
    }

  case 2: // Button was up, now down.
    if (button == HIGH) {
      *butnstate = 0;                 // no, not debounced; revert the state
      return false;                   // False alarm!
    }
    else { 
      if (millis() - *marker >= interval) {
        *butnstate = 1;               // jackpot!  update the state
        return true;                  // because we have the desired event!
      }
      else 
        return false;                 // not done yet; just move on
    }

  case 3: // Button was down, now up.
    if (button == LOW) {
      *butnstate = 1;                 // no, not debounced; revert the state
      return false;                   // False alarm!
    }
    else { 
      if (millis() - *marker >= interval) {
        *butnstate = 0;               // Debounced; update the state
        return false;                 // but it is not the event we want
      }
      else 
        return false;                 // not done yet; just move on
    }
  default:                            // Error; recover anyway
    {  
      *butnstate = 0;
      return false;                   // Definitely false!
    }
  }
}

void setup() {
  pinMode(led1Pin, OUTPUT);      
  pinMode(button1, INPUT); 
  pinMode(led2Pin, OUTPUT);      
  pinMode(button2, INPUT);      
  pinMode(led3Pin, OUTPUT);      
  pinMode(button3, INPUT);      
  pinMode(led4Pin, OUTPUT);      
  pinMode(button4, INPUT);        
  digitalWrite (led1Pin, LOW);
  digitalWrite (led2Pin, LOW);
  digitalWrite (led3Pin, LOW);
  digitalWrite (led4Pin, LOW);
}

void loop() {
  // Select LED if button debounced
  if (butndown(digitalRead(button1), &bcount1, &bstate1, 10UL )) {
    digitalWrite (led1Pin, HIGH);
    digitalWrite (led2Pin, LOW);
    digitalWrite (led3Pin, LOW);
    digitalWrite (led4Pin, LOW);
    delay(500);
  } 
  // Select LED if button debounced
  if (butndown(digitalRead(button2), &bcount2, &bstate2, 10UL )) {
    digitalWrite (led1Pin, LOW);
    digitalWrite (led2Pin, HIGH);
    digitalWrite (led3Pin, LOW);
    digitalWrite (led4Pin, LOW);
    delay(500);
  } 
  // Select LED if button debounced
  if (butndown(digitalRead(button3), &bcount3, &bstate3, 10UL )) {
    digitalWrite (led1Pin, LOW);
    digitalWrite (led2Pin, LOW);
    digitalWrite (led3Pin, HIGH);
    digitalWrite (led4Pin, LOW);
    delay(500);
  } 
  if (butndown(digitalRead(button4), &bcount4, &bstate4, 10UL )) {
    // Select LED if button debounced
    digitalWrite (led1Pin, LOW);
    digitalWrite (led2Pin, LOW);
    digitalWrite (led3Pin, LOW);
    digitalWrite (led4Pin, HIGH);
    delay(500);      
  } 
}

Oh wow. That code almost looks intimidating. Thank you so much for the help, as well as for the helpful comments. I will try my best to digest the code so I can modify my project by adding more buttons and lights.

Quick question, in my quick google research, INPUT_PULLUP is all about serial communication. So do I have to set up the Serial monitor for my project? My aim is to have a some sort of choice for a quiz, like, say, a quiz with multiple choices and you can only pick one. In this case since there is two buttons, its either answer #1 or answer #2, with the led lights telling the user "hey, you picked answer #1" or something like that where the user can see what he chose.

Thanks in advance.

Edit: Also, I am planning on duplicating this project, like having the choices for two people. Like both of them has their own two-button choices that they can choose from. But I will still run it on a single arduino. Can you give me any tips on how to do it. Thanks.

Dan015:
Quick question, in my quick google research, INPUT_PULLUP is all about serial communication.

In an Arduino it has nothing to do with Serial communication. It just enables the internal pull-up resistor for an I/O pin.

...R

Oh wow. I didn't know that. Thanks. Does this mean connecting the components to ground is actually optional? I can directly connect it to the I/O pins?

Dan015:
Does this mean connecting the components to ground is actually optional? I can directly connect it to the I/O pins?

That comment is too general for me to reply. What components? What do you mean by "it". Before you read Reply #3 what were you thinking you have to do?

What exactly do you want to do?

...R

Robin2:
What components? What do you mean by "it".

Oh sorry. I meant the 2 leds and 2 buttons in my project.

Robin2:
What exactly do you want to do?

From what I learned, you need to connect one pin to GND and one pin to the I/O. I'm asking if you can you can connect the I/O pin and have it work without the GND being connected. Like can you light up a led without connecting the GND. And if so, is there any trick to it. I was thinking of this since it looks like I can save myself some jumper wires.

Dan015:
Oh sorry. I meant the 2 leds and 2 buttons in my project.

From what I learned, you need to connect one pin to GND and one pin to the I/O. I'm asking if you can you can connect the I/O pin and have it work without the GND being connected. Like can you light up a led without connecting the GND. And if so, is there any trick to it. I was thinking of this since it looks like I can save myself some jumper wires.

Every electrical circuit needs two connections - one to let the electrons in and the other to let them out - just like water won't flow in a pipe unless there is an inlet and an outlet.

Beyond saying that I still don't have enough information to be more specific. For example you say "connect one pin the GND", but you don't say what the pin belongs to. Maybe posting a photo of a drawing of what you have in mind would make things easier. See this Simple Image Guide

LEDs also need a resistor in series with them to limit the current.

...R

Dan015:
Oh sorry. I meant the 2 leds and 2 buttons in my project.

led2Sw2.png

The execution of the following codes brings the internal pull-ups into circuit.

pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);

led2Sw2.png

Dan015:
Oh wow. That code almost looks intimidating.

Yeah. It is - it took a while to get it correct and neat - but now it is a set of "modules" designed so that you can cut-and-paste them to add more buttons with numbers in sequence.

While it does not show the "toggle" function - that is in another example - you can alter the individual modules to do that instead of putting one light on and turning the others off.

Dan015:
Quick question, in my quick google research, INPUT_PULLUP is all about serial communication.

Absolutely nothing whatsoever to do with serial communication. Don't know where you got that idea. :grinning:

Dan015:
Also, I am planning on duplicating this project, like having the choices for two people. Like both of them has their own two-button choices that they can choose from. But I will still run it on a single Arduino. Can you give me any tips on how to do it.

The whole point of this sort of coding - a general sort of "state machine" - is that since the main loop continuously cycles without interruption as long as the modules are correctly written, you can do many separate things simultaneously without interference. Just give each its own definitions and initialisation in setup(), and its own set of actions in loop().

In fact in the code as you see it, all you have to do to separate it into two parts, is to remove references to led3Pin and led4Pin in the button1 and button2 action modules, and remove references to led1Pin and led2Pin in the button3 and button4 action modules - and you have two separate systems.

Try it! :grinning:

Thank you so much everyone. I am very grateful for all the help I've received.

Apparently, the input_pullup that I searched was InputPullupSerial and apparently I confused everyone.

Thank you so much. I am unable to convey my thankfulness enough through words but I am very thankful.