Back to Projects
IntermediateESP32 DevKit V1
25 minutes build
ESP32 smart lamp switch
A button toggles a relay — the core of every smart switch.
Interactive Simulation
ESP32: button toggles a relayesp32-devkit-v1
Required Components Checklist
Assembly Steps
1
Relay module
VCC to VIN (5 V from USB), GND to GND, IN to GPIO26. Many modules accept a 3.3 V signal; check yours.
2
Button
Between GPIO4 and GND with INPUT_PULLUP.
3
Toggle on edges
Flip the state only when the button changes from HIGH to LOW.
Arduino Sketch
const int BUTTON = 4;
const int RELAY = 26;
bool on = false;
bool last = HIGH;
void setup() {
pinMode(BUTTON, INPUT_PULLUP);
pinMode(RELAY, OUTPUT);
Serial.begin(115200);
}
void loop() {
bool now = digitalRead(BUTTON);
if (last == HIGH && now == LOW) { // falling edge = a new press
on = !on;
digitalWrite(RELAY, on ? HIGH : LOW);
Serial.println(on ? "Lamp ON" : "Lamp OFF");
delay(50); // simple debounce
}
last = now;
}
Challenges & Extensions
Ready to take this project further? Try these challenges:
- •Add an auto-off timer.
- •Remember the state across resets with Preferences (real board).
- •Control it from a web page (see the Connected ESP32 course).