To read a button push with an Arduino, the easiest and cleanest method uses the microcontroller's built-in internal pull-up resistor (INPUT_PULLUP). This eliminates the need for an external resistor, simplifying your physical circuit to just two wires. [1, 2, 3]
The Wiring Circuit
Connect your hardware directly without any external resistors: [1, 2]
/*
Button with Internal Pullup
Turns on and off a light emitting diode (LED) connected to digital pin 13,
when pressing a pushbutton attached to pin 2.
The circuit:
- LED attached from pin 13 to ground through 220 ohm resistor
- pushbutton attached to pin 2 from ground (no external resistors needed)
- Note: on most Arduinos there is already an LED on the board attached to pin 13.
https://docs.arduino.cc/built-in-examples/digital/Button/
*/
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input with internal pullup:
pinMode(buttonPin, INPUT_PULLUP); //creates an internal pullup resistor
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// With INPUT_PULLUP, a press pulls the pin to LOW:
if (buttonState == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}