A Push Button is a simple input device used to control circuits. When pressed, it makes a connection between its terminals and sends a digital signal to the ESP32.
In this tutorial, we’ll use a Push Button connected to GPIO 5 of ESP32 DOIT DevKit v1. When the button is pressed, the onboard LED (GPIO 2) will turn ON, and when released, the LED will turn OFF.
⚠️ Note: ESP32 has internal pull-up and pull-down resistors. For simplicity, we will use the internal pull-down in code (no external resistor required).
// Push Button with ESP32 DOIT DevKit v1
// Button at GPIO 5, Onboard LED at GPIO 2
int buttonPin = 5; // Push Button connected to GPIO 5
int ledPin = 12; // LED at GPIO 12
int buttonState = 0; // Variable to store button state
void setup() {
pinMode(buttonPin, INPUT_PULLDOWN); // Use internal pull-down resistor
pinMode(ledPin, OUTPUT); // Set LED as output
}
void loop() {
buttonState = digitalRead(buttonPin); // Read button input
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // Turn ON LED when button pressed
} else {
digitalWrite(ledPin, LOW); // Turn OFF LED when button released
}
}
int buttonPin = 5;
int ledPin = 12;
Assign GPIO 5 for button and GPIO 12 for onboard LED.
Setup Function
pinMode(buttonPin, INPUT_PULLDOWN);
pinMode(ledPin, OUTPUT);
INPUT_PULLDOWN
enables ESP32’s internal pull-down resistor.Loop Function
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) { ... }
Reads the button state.
If pressed (HIGH), LED turns ON.
If not pressed (LOW), LED turns OFF.
Problem | Cause | Solution |
---|---|---|
LED not responding | Wrong GPIO wiring | Ensure button is connected to GPIO 5 |
LED always ON | No pull-down resistor | Use INPUT_PULLDOWN or external 10kΩ resistor |
LED flickers randomly | Button bouncing | Use software debouncing (future tutorial) |
Wrong LED | Using external LED without resistor | Add 220Ω resistor for external LED |
Yes, connect an LED to any GPIO (with a 220Ω resistor) and update the code.
INPUT_PULLDOWN
instead of external resistor?ESP32 has internal pull-up/pull-down resistors, so no extra components needed.
Check if you accidentally connected it to 3.3V without pull-down.
You can use debouncing techniques in hardware (capacitor) or software (code delay/filter).
Yes, you can connect multiple buttons to different GPIOs and read them separately.