Wrong serial output when pressing push buttons

Hi,

I have set 4 push buttons up on my breadboard, which I am trying to get to return 1, 2, 3 or 4, depending on which button is pressed.

Sometimes, the buttons work as intended, but sometimes, button 4 returns "4", while buttons 3, 2 and 1 all return "1". I have no idea why this is happening, and would really appreciate some help in understanding what I am doing wrong.

Here is my code:

int buttonOne = 2;
int buttonTwo = 3;
int buttonThree = 4;
int buttonFour = 5;
bool pressed = 0;
int pressedButton = 0;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(buttonOne, INPUT);
  pinMode(buttonTwo, INPUT);
  pinMode(buttonThree, INPUT);
  pinMode(buttonFour, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  
  if(digitalRead(buttonOne) == 1 && pressed != 1){
    pressed = 1;
    pressedButton = buttonOne;
    Serial.println(1);
  }
  
  if(digitalRead(buttonTwo) == 1 && pressed != 1){
    pressed = 1;
    pressedButton = buttonTwo;
    Serial.println(2);
  }
  
  if(digitalRead(buttonThree) == 1 && pressed != 1){
    pressed = 1;
    pressedButton = buttonThree;
    Serial.println(3);
  }
  
  if(digitalRead(buttonFour) == 1 && pressed != 1){
    pressed = 1;
    pressedButton = buttonFour;
    Serial.println(4);
  }
 
  if(digitalRead(pressedButton) == 0){
    pressed = 0;
    pressedButton = 0;
  }

  delay(100);
}

This is the setup on my breadboard:

The yellow wire is a 5V output, the blue wire is hooked up to pin 5, green is pin 4, purple is pin 3, orange is pin 2, and white is ground.

Sorry if this is posted in the wrong category, I wasn't quite sure where to post this!

You don't wire up push buttons like that.

You wire them between the input and ground and use the internal pull up resistors in the pinMode call.

Then a push returns a LOW and no pus returns HIGH.

1 Like

Wiring those 6mm tactile push buttons:

1 Like

The digitalRead() does not return a 1 or 0, it returns HIGH or LOW.
A bool variable can be true or false.
I know that it is all the same, but I prefer normal code. Writing code is not about taking shortcuts.

The name of a variable for a pin could have the word "Pin" in it to avoid confusion.

There is some kind of bug in the sketch.
When the button is released, the 'pressedButton' is set to 0. Next time there is a digitalRead() for pin 0.

  if(digitalRead(pressedButton) == 0){  // bug: could be reading from pin 0
    pressed = 0;
    pressedButton = 0;     // bug: next time the digitalRead will use it
  }

I made your project in Wokwi simulation with pulldown resistors (for now). As the others wrote, a button with one leg to GND and a pullup resistor is better.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.