Web / button relay switch

Switch a low-voltage load from a web page, the phone or a physical button; the base for any remote control.

Smart home Board: ESP32 DevKit V1 (WROOM-32) Level: ●○○ ⏱ 1 h

⚠ Caution

Switch only low-voltage loads yourself. For mains loads use a certified isolated module in a box or call an electrician.

Small project, big list of ways it can go wrong

A relay on a web page is the "hello world" of home automation, and it is also where most real-life problems appear. The first is what the relay does at power-up. Some ESP32 pins pulse during boot, and your kettle clicks on and off at every reset. Pick a pin that is stable, and write the last state to flash so that after an outage the device returns to what you expect.

Checklist before it goes into a wall

  • Use a relay module with an optocoupler and a separate supply for the coil; many modules need 5 V for the coil and 3.3 V for the signal, check which one yours is.
  • A physical button should work even when Wi-Fi is gone. Debounce it in software.
  • Put a token or a password on the page. An open HTTP switch is visible to everyone on the local network.
  • For motors and transformers add a snubber across the load; arcing wears the contacts fast.

The same sketch becomes a lamp controller, a gate pulse generator or the output of a bigger scheme such as the router watchdog.

Components

  • ESP32 DevKit V1 (30 pin, WROOM-32)
  • Relay module 1-channel 5V (opto-isolated)
  • Tactile buttons (set)
  • Dupont jumper wires (M-F, M-M)

Wiring

Module Module pin ESP32 pin Note
Relay IN signal GPIO26 active LOW
Relay VCC / GND 5V / GND
Button one side GPIO14 other side to GND

Code

#include <WiFi.h>

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";

bool connectWiFi(uint32_t timeoutMs = 20000) {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  uint32_t t0 = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t0 < timeoutMs) {
    delay(250);
    Serial.print(".");
  }
  Serial.println();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("IP: ");
    Serial.println(WiFi.localIP());
    return true;
  }
  return false;
}
#include <WebServer.h>

WebServer server(80);
String buildJson();   // implemented in the project below

String num(float v, int d = 1) { return isnan(v) ? String("null") : String(v, d); }

const char PAGE_HTML[] PROGMEM = R"rawliteral(
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32</title>
<style>body{font-family:system-ui;background:#0b0f14;color:#e6edf3;margin:20px}table{border-collapse:collapse}td{padding:6px 14px;border-bottom:1px solid #223}button,input{font-size:16px;padding:8px 14px;margin:4px;border-radius:6px;border:1px solid #345;background:#16202b;color:#e6edf3}</style>
</head><body><h2>ESP32</h2><table id="t"></table>
bool on = false;
String buildJson() { return String("{"relay":"") + (on ? "on" : "off") + ""}"; }

<script>
function load(){fetch('/json').then(r=>r.json()).then(d=>{let h='';for(const k in d){h+='<tr><td>'+k+'</td><td>'+d[k]+'</td></tr>';}document.getElementById('t').innerHTML=h;});}
load();setInterval(load,2000);
</script></body></html>
)rawliteral";

void startWeb() {
  server.on("/", []() { server.send_P(200, "text/html", PAGE_HTML); });
  server.on("/json", []() { server.send(200, "application/json", buildJson()); });
  server.begin();
}
const int PIN_RELAY = 26, PIN_BTN = 14;
void setRelay(bool v) { on = v; digitalWrite(PIN_RELAY, v ? LOW : HIGH); }
void setup() {
  pinMode(PIN_RELAY, OUTPUT); setRelay(false);
  pinMode(PIN_BTN, INPUT_PULLUP);
  Serial.begin(115200);
  connectWiFi();
  server.on("/toggle", []() { setRelay(!on); server.send(200, "text/plain", on ? "on" : "off"); });
  startWeb();
}
void loop() {
  server.handleClient();
  static bool last = true; bool b = digitalRead(PIN_BTN);
  if (last && !b) { setRelay(!on); delay(200); }
  last = b;
}

Build tips

  • Give the board a fixed DHCP reservation in the router.
  • Choose the right relay logic (active LOW) in the code.

What you need

Buy the parts kit · Estimated total: $7.50

ESP32 DevKit V1 (30 pin, WROOM-32) × 1
$4.00
Buy at AliExpress Buy at Amazon.com
Relay module 1-channel 5V (opto-isolated) × 1
$1.50
Buy at AliExpress Buy at Amazon.com
Tactile buttons (set) × 1
$0.50
Buy at AliExpress Buy at Amazon.com
Dupont jumper wires (M-F, M-M) × 1
$1.50
Buy at AliExpress Buy at Amazon.com
🇺🇦 Ukraine🌍 Other countries

Ukraine: we buy and sell these parts ourselves, order them on this site.

Some links are affiliate links: we may earn a commission at no extra cost to you.

Related ideas

⚠ Caution

Switch only low-voltage loads yourself. For mains loads use a certified isolated module in a box or call an electrician.

Telegram remote control and status

A Telegram bot on the ESP32 reports status on request and switches a relay with commands from your phone, with no server and no port forwarding.

  • Board ESP32-C3 SuperMini
  • Level ●○○ Beginner
  • Build time 1–2 h
Pick parts / kit
⚠ Caution

Switch only low-voltage loads yourself. For mains loads use a certified isolated module in a box or call an electrician.

Router and Starlink watchdog

Pings the internet and power-cycles the router or ONU through a relay when the connection hangs, with a Telegram notice.

  • Board ESP32-C3 SuperMini
  • Level ●○○ Beginner
  • Build time 1 h
Pick parts / kit
⚠ Caution

Switch only low-voltage loads yourself. For mains loads use a certified isolated module in a box or call an electrician.

Gate and garage door status with remote pulse

Two reed switches report open and closed, a relay gives the opener a pulse, and a message tells you when the gate was left open.

  • Board ESP32-C3 SuperMini
  • Level ●○○ Beginner
  • Build time 1–2 h
Pick parts / kit

← All module ideas →

Comments

No comments yet. Share your experience or ask a question.

Comments are moderated.