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
Image is developed using Fritzing. Click to enlarge image
The output on Serial Monitor
How to solve it?
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
|1 × Arduino UNO Buy on Amazon|
|1 × Arduino MEGA Buy on Amazon|