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!