Intermediateesp32

Smart Light Switch with ESP32

Replace your regular light switch with a WiFi-controlled smart switch using ESP32 and relay module.

3-4 hours
$15-30
Sarah Mitchell
Smart Light Switch with ESP32

Parts List

  • ESP32 DevKit
  • Relay Module (1-Channel)
  • Momentary Push Button
  • Wall Mount Box
  • Wires

Step-by-Step Instructions

1

Safety First

Turn off the circuit breaker controlling the light circuit you plan to modify and verify the power is off using a non-contact voltage tester. Never work on mains wiring while the circuit is energized, as this poses a serious risk of electric shock or fire. If you are not comfortable working with mains voltage, consult a licensed electrician to assist with the wiring portion of this project.

2

Wire Relay Module

Disconnect the existing wall switch and wire the relay module's COM and NO terminals in series with the live wire feeding the light fixture. Connect the relay module's IN pin to GPIO pin 26 on the ESP32 and power it from the ESP32's 5V output. Secure all wire connections with wire nuts or terminal blocks and ensure no bare copper is exposed before closing the junction box.

3

Program ESP32

Write an Arduino sketch that connects the ESP32 to your home WiFi network and starts a web server on port 80. Create a single toggle endpoint that switches the relay state between on and off when accessed. Store the current light state in a variable so the web interface can display the correct status and the relay knows its current position after a power cycle.

#include <WiFi.h>
#include <WebServer.h>

const int relayPin = 26;
bool lightOn = false;
WebServer server(80);

void handleToggle() {
  lightOn = !lightOn;
  digitalWrite(relayPin, lightOn ? HIGH : LOW);
  server.send(200, "application/json",
    "{\"on\":" + String(lightOn ? "true" : "false") + "}");
}

void handleStatus() {
  server.send(200, "application/json",
    "{\"on\":" + String(lightOn ? "true" : "false") + "}");
}

void setup() {
  pinMode(relayPin, OUTPUT);
  WiFi.begin("SSID", "password");
  while (WiFi.status() != WL_CONNECTED) delay(500);
  server.on("/toggle", handleToggle);
  server.on("/status", handleStatus);
  server.begin();
}

void loop() { server.handleClient(); }
4

Add Physical Button

Wire a momentary push button between GPIO pin 27 and ground, using the ESP32's internal pull-up resistor. Add an interrupt service routine that toggles the relay state on each button press, providing manual override capability independent of the web interface. Mount the button on the wall plate or enclosure so it is accessible without removing the cover.