What you will build
A push button that toggles the LED from Project 01: press once for on, press again for off. You will learn how a microcontroller reads the outside world and why buttons need "debouncing".
How it works
GPIO 27 is an input with the ESP32's internal pull-up resistor, so it reads HIGH when the button is released. Pressing the button connects the pin to GND and it reads LOW. The sketch watches for the moment the reading changes from HIGH to LOW, ignores the 30 ms of electrical bounce that follows, and flips the LED state.
Parts
| Part | Qty | Purpose | Required |
|---|---|---|---|
| Everything from Project 01 | — | LED circuit | Yes |
| 4-pin tactile push button (6–12 mm) | 1 | Input | Yes |
| Jumper wires | 2 | Connections | Yes |
Build steps
- Keep the LED circuit from Project 01 on GPIO 26.
- Place the button across the centre gap of the breadboard.
- Connect one leg of the button to GPIO 27.
- Connect the diagonally opposite leg to GND. No external resistor is needed.
- Upload the code. Open Tools → Serial Monitor at 115200 baud.
- Checkpoint: each press prints
LED: ONorLED: OFFand the LED follows. - Change
DEBOUNCE_MSto0and press quickly: you may see double toggles. Set it back to30.
Try it in the browser
Playground Simulation. Click the virtual button on the breadboard to toggle the virtual LED. The Serial panel shows the same messages as the real board.
Open Simulator PlaygroundCode
Download button-controlled-light.ino
// Button-controlled Light — XBOTNOW
// Board: ESP32-DevKitC V4 · Core: esp32 v3.x
const int LED_PIN = 26;
const int BUTTON_PIN = 27; // button to GND, internal pull-up
const unsigned long DEBOUNCE_MS = 30;
bool ledOn = false;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChange = 0;
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastChange = millis(); // input moved: restart the timer
lastReading = reading;
}
if (millis() - lastChange > DEBOUNCE_MS && reading != stableState) {
stableState = reading;
if (stableState == LOW) { // a clean press
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
Serial.println(ledOn ? "LED: ON" : "LED: OFF");
}
}
}
Troubleshooting
| Symptom | Likely cause | Check |
|---|---|---|
| LED toggles on its own | Pin floating | Confirm INPUT_PULLUP and the GND wire |
| Nothing happens on press | Button legs on the same internal side | Rotate the button 90° or use diagonal legs |
| Sometimes toggles twice | Bounce | Raise DEBOUNCE_MS to 50 |
Safety and limitations
Low-voltage logic only. Never wire a button to 5 V on an ESP32 input: the pins are 3.3 V.
Checklist
Next project
Mood Lamp: go beyond on/off and mix colours with a knob.

