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

Arduino Button Wiring Diagram

This image is created using Fritzing. Click to enlarge image

The output on Serial Monitor

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
0 1 1 0 1 0 0
Ln 11, Col 1
Arduino Uno on COM15
2

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:

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 .

The Best Arduino Starter Kit

※ OUR MESSAGES