E8-11ESP8266Beginner

ESP8266 Web Relay Switch: Tap on Your Phone and the NodeMCU Switches the Relay

Tap the single button on a web page and the relay pulls in with a click; tap again and it releases. The NodeMCU V3 joins your home Wi-Fi and lets you run the relay from your phone. A relay is a switch: it turns the 5 V fan or lamp wired to its COM and NO terminals on and off. The module takes its power from VIN (5 V), and because most modules work inverted the code has one setting for that. The ESP8266 only joins 2.4 GHz networks.

0.0(0)
ESP8266 Web Relay Switch: Tap on Your Phone and the NodeMCU Switches the Relay
Lighting an LED is nice, but a pin of the board can only supply a few milliamps; a fan, a pump or a lamp needs a switch. In this project you meet that switch, the relay: you learn why the module wants its own 5 V supply, what an inverted module is and which order the code follows so the board does not pull the relay in by accident at start. The same method is the base of a smart plug, a watering pump, an aquarium light and every device that is switched from a distance.

Video

Circuit Diagram

ESP8266 Web Relay Switch: Tap on Your Phone and the NodeMCU Switches the Relay - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   ESP8266 Web Relay Switch: Tap on Your Phone and the NodeMCU Switches the Relay
4// ─────────────────────────────────────────
5// The NodeMCU joins your home Wi-Fi and serves a page with a single
6// button. Open the board's IP address in the browser of a phone on the
7// same network and tap the button: the relay pulls in, and another tap
8// releases it. A relay is a switch; it turns the fan or lamp wired to its
9// COM and NO terminals on and off.
10//
11// Pins:
12//   D5 (GPIO14) -> relay module IN (S)
13//   GND         -> relay module GND (-)
14//   VIN (5 V)   -> relay module VCC (+)
15
16#include <ESP8266WiFi.h>
17#include <ESP8266WebServer.h>
18
19// ============ WI-FI NETWORK ============
20// Write the name and password of your own network inside the quotes. The ESP8266 only joins 2.4 GHz
21// networks.
22const char *const WIFI_SSID = "YOUR_WIFI_NAME";
23const char *const WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
24const unsigned long WIFI_HINT_MS = 20000; // Time until the hint (ms)
25
26// ============ PINS ============
27// D3, D4 and D8 have a special job while the board starts; a relay there can click on and off
28// during boot. The relay uses the spare pin D5.
29const uint8_t PIN_RELAY = D5;             // GPIO14
30// Most relay modules work inverted: the relay pulls in when the IN leg goes LOW. Write false if
31// yours pulls in on HIGH.
32const bool RELAY_ACTIVE_LOW = true;
33
34// ============ PAGE TEXTS ============
35const char TEXT_TITLE[] = "Relay Switch";
36const char TEXT_ON[] = "ON";
37const char TEXT_OFF[] = "OFF";
38const char TEXT_NOT_FOUND[] = "Page not found";
39
40// ============ WEB PAGE ============
41// The fixed top of the page: UTF-8 encoding, a phone-friendly width and the looks (CSS).
42const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
43<meta name="viewport" content="width=device-width,initial-scale=1"><title>ESP8266</title>
44<style>
45body{margin:0;padding:28px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
46text-align:center}
47h1{font-size:26px;margin:0 0 28px}
48a{display:block;width:240px;height:240px;margin:0 auto;border-radius:50%;background:#334155;
49color:#f8fafc;font-size:36px;font-weight:bold;line-height:240px;text-decoration:none}
50a.on{background:#22c55e;color:#0f172a}
51</style></head><body>)rawliteral";
52
53ESP8266WebServer server(80);              // Port 80: the web default
54bool relayOn = false;
55bool wifiUp = false;
56bool hintDone = false;
57
58// Switches the relay on or off. The level written to the pin depends on the kind of module.
59void setRelay(bool on) {
60  relayOn = on;
61  digitalWrite(PIN_RELAY, on == RELAY_ACTIVE_LOW ? LOW : HIGH);
62}
63
64// Builds the page and sends it to the browser: one big button that shows the current state.
65void sendPage() {
66  String html = PAGE_HEAD;
67  html += "<h1>";
68  html += TEXT_TITLE;
69  html += relayOn ? "</h1><a class=\"on\" href=\"/toggle\">" : "</h1><a href=\"/toggle\">";
70  html += relayOn ? TEXT_ON : TEXT_OFF;
71  html += "</a></body></html>";
72  // The browser must not keep a copy of the page; every tap has to reach the board.
73  server.sendHeader("Cache-Control", "no-store");
74  server.send(200, "text/html; charset=utf-8", html);
75}
76
77// An address that has done its job sends the browser back to the root page (303). The address bar
78// always shows / and reloading the page does not repeat the last tap.
79void goHome() {
80  server.sendHeader("Location", "/");
81  server.send(303);
82}
83
84// Every address has its own function; it runs when the browser asks for that address.
85void handleRoot() {
86  sendPage();
87}
88
89// The address of the button: flips the state (off if it was on, on if it was off).
90void handleToggle() {
91  setRelay(!relayOn);
92  Serial.println(relayOn ? "Relay on" : "Relay off");
93  goHome();
94}
95
96void handleNotFound() {
97  server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
98}
99
100// Watches the connection: prints the IP address once connected and reports a drop. The ESP8266
101// rejoins a lost network by itself.
102void checkWifi() {
103  bool up = WiFi.status() == WL_CONNECTED;
104  if (up && !wifiUp) {
105    hintDone = true;
106    Serial.println("Wi-Fi connected");
107    Serial.print("Open in your browser: ");
108    Serial.print("http://");
109    Serial.println(WiFi.localIP());
110  } else if (!up && wifiUp) {
111    Serial.println("Wi-Fi lost. Reconnecting");
112  }
113  wifiUp = up;
114
115  if (!up && !hintDone && millis() > WIFI_HINT_MS) {
116    hintDone = true;
117    Serial.println("Could not join the Wi-Fi");
118    Serial.println("Check the network name and password");
119    Serial.println("The ESP8266 only sees 2.4 GHz networks");
120  }
121}
122
123void setup() {
124  Serial.begin(115200);
125  // The level is written first and the pin becomes an output after that, so the relay does not
126  // click even for a moment at start.
127  setRelay(false);
128  pinMode(PIN_RELAY, OUTPUT);
129  Serial.println();
130  Serial.println("Web relay switch");
131  if (strncmp(WIFI_SSID, "YOUR_", 5) == 0) {
132    Serial.println("Put your Wi-Fi name and password in the code");
133  }
134  Serial.println("Connecting to Wi-Fi");
135  // The board opens no network of its own, it joins yours
136  WiFi.mode(WIFI_STA);
137  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
138
139  server.on("/", handleRoot);
140  server.on("/toggle", handleToggle);
141  server.onNotFound(handleNotFound);
142  server.begin();
143}
144
145// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
146void loop() {
147  checkWifi();
148  server.handleClient();                  // Handles a waiting request
149}
150

FAQ

Why does the relay module go to VIN?

The coil inside the relay needs 5 V and about 70 mA to pull in. The 3V3 rail and the pins of the board cannot supply that; if pushed, the board restarts. VIN passes on the 5 V from USB, so the computer or the adapter feeds the coil. The pin of the board only tells the module to pull in or release, it does not carry the current.

What is an inverted module?

On most relay modules the relay pulls in when the IN leg goes LOW and releases on HIGH. The code knows this through the RELAY_ACTIVE_LOW constant and picks the right level by itself. If the relay releases while the page says ON, your module works the straight way: set the constant to false and upload the code again.

What can I connect to the relay?

A relay is like a switch: COM is the common terminal and it joins NO when the relay pulls in. Cut the plus wire of a 5 V fan or a USB lamp and put the two ends into COM and NO. Stay with low voltage (5 to 12 V). Mains voltage can kill; never touch anything wired to the mains without an adult who is an expert.

Why does the relay not click when the board starts?

setup writes the release level first and makes the pin an output after that. In the opposite order the pin would give LOW the moment it became an output and an inverted module would pull in for an instant. The relay is also on D5: D3, D4 and D8 have a special job while the board starts, and a relay there can click by itself during boot.