I am making a sensor that can sense 3 buttons separately, I wanted to print the number of the button I am pushing to the Serial Monitor, but I did something wrong wiring my Arduino. Here is my code (I think there's nothing wrong with that part of the project):
int LedPin = 12;
int buttonPin = 2;
int buttonPin2 = 3;
int buttonPin3 = 4;
//int buttonPin4 = 5;
int buttonState = 0;
int buttonState2 = 0;
int buttonState3 = 0;
//int buttonState4 = 0;
void setup()
{
Serial.begin(9600);
pinMode(LedPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
//pinMode(buttonPin4, INPUT);
}
void loop()
{
buttonState = digitalRead(buttonPin);
buttonState2 = digitalRead(buttonPin2);
buttonState3 = digitalRead(buttonPin3);
//buttonState4 = digitalRead(buttonPin4);
Serial.print(buttonState);
Serial.print(buttonState2);
Serial.println(buttonState3);
//delay(1000);
if (buttonState == HIGH) {
//Serial.println("1");
digitalWrite(LedPin, HIGH);
} else {
digitalWrite(LedPin, LOW);
}
if (buttonState2 == HIGH) {
//Serial.println("2");
digitalWrite(LedPin, HIGH);
} else {
digitalWrite(LedPin, LOW);
}
if (buttonState3 == HIGH) {
//Serial.println("3");
digitalWrite(LedPin, HIGH);
} else {
digitalWrite(LedPin, LOW);
}
/*if (buttonState4 == HIGH) {
Serial.println("4");
digitalWrite(Pin, HIGH);
} else {
digitalWrite(Pin, LOW);
}*/
}
Problem:
And some pictures with Serial output (when I press any button it outputs 111, if I don't press anything it writes 000)
Top comments (2)
You need pull low resistors.
Have a 10k resistor run from ground to the input. Do that for each input using a total of three resistors.
Now connect one end of the switch to +5v. And the other end of the switch run to the input. Again, do that for each input.
So when the switch is open the input will read low. When the switch is closed the input will read high.
Thanks man!