Read a Button
Use a push button to control an LED. Covers digital input, pull-down resistors, and software debouncing.
1Digital Input
While digital output lets you control voltage on a pin, digital input lets you read voltage on a pin. You configure a pin as INPUT with pinMode(), then read it with digitalRead(), which returns either HIGH (button pressed, ~5V) or LOW (button released, 0V).
int buttonState = digitalRead(2); // Returns HIGH or LOWNote: Digital pins can only read two states: HIGH (≥ 3V reads as HIGH on a 5V Arduino) or LOW (≤ 1.5V reads as LOW).
2Pull-down Resistors
Without a resistor, a floating input pin picks up electrical noise from the environment, causing random HIGH/LOW readings even when nothing is pressed. A pull-down resistor (typically 10kΩ) connects the input pin to GND, forcing it to read LOW when the button is open.
When you press the button, 5V connects directly to the pin, overriding the resistor's pull to GND and reading HIGH.
Note: Arduino has built-in pull-up resistors accessible via INPUT_PULLUP mode — this reverses the logic: unpressed = HIGH, pressed = LOW.
3Building the Circuit
- Button pin 1 → Pin 2 on Arduino AND one leg of 10kΩ resistor
- Other leg of 10kΩ resistor → GND
- Button pin 2 → 5V
- LED (with 220Ω) → Pin 13
4The Code
const int buttonPin = 2;
const int ledPin = 13;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int state = digitalRead(buttonPin);
if (state == HIGH) {
digitalWrite(ledPin, HIGH); // Button pressed — LED on
} else {
digitalWrite(ledPin, LOW); // Button released — LED off
}
}5Software Debouncing
Mechanical buttons don't cleanly switch — they 'bounce' between HIGH and LOW for a few milliseconds when pressed. This causes your code to register multiple presses for a single click.
The simplest fix: record the time of the last stable reading and ignore changes that happen within 50ms of it.
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
int lastButtonState = LOW;
int buttonState = LOW;
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
buttonState = reading;
}
digitalWrite(ledPin, buttonState);
lastButtonState = reading;
}Skill Check
8 questions · Up to 180 XP
Q1.What does digitalRead() return?
Q2.What is the purpose of a pull-down resistor?
Q3.What does INPUT_PULLUP mode do?
Q4.What causes button bouncing?
Q5.What does millis() return?
Q6.With a pull-down resistor, what does the pin read when the button is NOT pressed?
Q7.What is a typical debounce delay?
Q8.What value resistor is typically used as a pull-down?
Sign in to earn XP for your answers.