Arduino - Button value changes between 0 and 1 randomly
I used Arduino to read the state from a button. The reading state changes between 0 and 1 randomly and constantly. The belows are Arduino code and the wiring diagram
#define BUTTON_PIN 7
void setup() {
Serial.begin(9600);
// initialize the button pin as a digital input pin
pinMode(BUTTON_PIN, INPUT);
}
void loop() {
// read the value of the button
int buttonValue = digitalRead(BUTTON_PIN);
Serial.println(buttonValue);
}
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
The output on Serial Monitor
COM6
0
1
1
0
1
0
0
Autoscroll
Clear output
9600 baud
Newline
How to solve it?
Answer
Your problem is known as the floating input problem. When you connect an Arduino pin to a button/switch without using any pull-up or pull-down resistor, this problem will happen.
How to solve
There are three way to solve it with Arduino:
- Use an external pull-down resistor on the Arduino pin ⇒ you need to modify the wiring diagram
- Use an external pull-up resistor on the Arduino pin ⇒ you need to modify the wiring diagram
- Use an internal pull-up resistor on the Arduino pin ⇒ you do NOT need to modify the wiring diagram, you just need to modify the code.
The below code used an internal pull-up resistor to solve the above problem
#define BUTTON_PIN 7
void setup() {
Serial.begin(9600);
// initialize the button pin as a digital input pin and enable the internal pull-up resistor
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
// read the value of the button
int buttonValue = digitalRead(BUTTON_PIN);
Serial.println(buttonValue);
}
Buy Arduino
1 × Arduino UNO Buy on Amazon | |
1 × Arduino MEGA Buy on Amazon |
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.
Additionally, some links direct to products from our own brand, DIYables.