ESP8266 Web Traffic Light: Red, Yellow, Green and an Automatic Cycle from Your Phone with a NodeMCU
Run a three-color traffic light from your phone's browser. The NodeMCU V3 joins your home Wi-Fi and its page shows three round lamps: tap one and the red, yellow or green LED turns on or off. The AUTO button starts the cycle of a real traffic light: red for 3 s, green for 3 s, yellow for 1.5 s. During the cycle the page reloads every second and the board keeps answering your taps. The ESP8266 only joins 2.4 GHz networks.

Video
Circuit Diagram

Source Code
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// ESP8266 Web Traffic Light: Red, Yellow, Green and an Automatic Cycle from Your Phone with a NodeMCU
4// ─────────────────────────────────────────
5// The NodeMCU joins your home Wi-Fi and serves a traffic light page. Open
6// the board's IP address in the browser of a phone on the same network and
7// you get three round lamps: tap one and that LED turns on or off. The
8// button below starts the automatic cycle: red, green, yellow. The board
9// keeps answering the page during the cycle because it times it with
10// millis, not delay.
11//
12// Pins:
13// D7 (GPIO13) -> 220 ohm resistor -> red LED anode (long leg)
14// D6 (GPIO12) -> 220 ohm resistor -> yellow LED anode (long leg)
15// D5 (GPIO14) -> 220 ohm resistor -> green LED anode (long leg)
16// GND -> cathodes of the three LEDs (short leg, minus rail)
17
18#include <ESP8266WiFi.h>
19#include <ESP8266WebServer.h>
20
21// ============ WI-FI NETWORK ============
22// Write the name and password of your own network inside the quotes. The ESP8266 only joins 2.4 GHz
23// networks.
24const char *const WIFI_SSID = "YOUR_WIFI_NAME";
25const char *const WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
26const unsigned long WIFI_HINT_MS = 20000; // Time until the hint (ms)
27
28// ============ PINS ============
29// D3, D4 and D8 have a special job while the board starts; the lamps use the spare pins D5, D6 and
30// D7.
31const uint8_t PIN_RED = D7; // GPIO13
32const uint8_t PIN_YELLOW = D6; // GPIO12
33const uint8_t PIN_GREEN = D5; // GPIO14
34
35// ============ AUTO CYCLE ============
36// How long each lamp stays on in the automatic cycle (ms). The order: red, green, yellow.
37const unsigned long PHASE_MS[] = {3000, 3000, 1500};
38
39// ============ PAGE TEXTS ============
40const char TEXT_TITLE[] = "Traffic Light";
41const char TEXT_AUTO[] = "AUTO";
42const char TEXT_STOP[] = "STOP";
43const char TEXT_NOT_FOUND[] = "Page not found";
44
45// ============ WEB PAGE ============
46// The fixed top of the page: UTF-8 encoding, a phone-friendly width and the looks (CSS).
47const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
48<meta name="viewport" content="width=device-width,initial-scale=1"><title>ESP8266</title>
49<style>
50body{margin:0;padding:28px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
51text-align:center}
52h1{font-size:26px;margin:0 0 20px}
53div{width:136px;margin:0 auto 24px;padding:16px 0 2px;border-radius:40px;background:#1e293b}
54div a{display:block;width:104px;height:104px;margin:0 auto 14px;border-radius:50%;
55background:#334155}
56a.red.on{background:#ef4444}
57a.yellow.on{background:#facc15}
58a.green.on{background:#22c55e}
59a.b{display:block;max-width:300px;margin:0 auto;padding:26px 0;border-radius:24px;
60background:#334155;color:#f8fafc;font-size:28px;font-weight:bold;text-decoration:none}
61a.b.on{background:#38bdf8;color:#0f172a}
62</style></head><body>)rawliteral";
63
64ESP8266WebServer server(80); // Port 80: the web default
65bool redOn = false;
66bool yellowOn = false;
67bool greenOn = false;
68bool autoMode = false;
69uint8_t phase = 0; // 0 red, 1 green, 2 yellow
70unsigned long phaseStart = 0;
71bool wifiUp = false;
72bool hintDone = false;
73
74// Sets all three lamps at once and reports it on the Serial port: 1 is on, 0 is off.
75void setLamps(bool red, bool yellow, bool green) {
76 redOn = red;
77 yellowOn = yellow;
78 greenOn = green;
79 digitalWrite(PIN_RED, red ? HIGH : LOW);
80 digitalWrite(PIN_YELLOW, yellow ? HIGH : LOW);
81 digitalWrite(PIN_GREEN, green ? HIGH : LOW);
82 Serial.print("Red Yellow Green: ");
83 Serial.print(red);
84 Serial.print(yellow);
85 Serial.println(green);
86}
87
88// Switches the automatic cycle off; it leaves the lamps alone.
89void stopAuto() {
90 if (autoMode) {
91 autoMode = false;
92 Serial.println("Auto cycle stopped");
93 }
94}
95
96// Adds one round lamp to the page. The color name gives both the looks (CSS class) and the address:
97// /red for "red". A lit lamp also gets the class "on".
98void addLamp(String &html, const char *color, bool on) {
99 html += "<a class=\"";
100 html += color;
101 html += on ? " on\" href=\"/" : "\" href=\"/";
102 html += color;
103 html += "\"></a>";
104}
105
106// Builds the page for the current state and sends it to the browser: three lamps and the auto
107// button.
108void sendPage() {
109 String html = PAGE_HEAD;
110 html += "<h1>";
111 html += TEXT_TITLE;
112 html += "</h1><div>";
113 addLamp(html, "red", redOn);
114 addLamp(html, "yellow", yellowOn);
115 addLamp(html, "green", greenOn);
116 html += autoMode ? "</div><a class=\"b on\" href=\"/auto\">" : "</div><a class=\"b\" href=\"/auto\">";
117 html += autoMode ? TEXT_STOP : TEXT_AUTO;
118 html += "</a></body></html>";
119 // The browser must not keep a copy of the page; every tap has to reach the board.
120 server.sendHeader("Cache-Control", "no-store");
121 // During the automatic cycle the browser reloads the page every second; the lamps on the screen
122 // follow the LEDs.
123 if (autoMode) {
124 server.sendHeader("Refresh", "1");
125 }
126 server.send(200, "text/html; charset=utf-8", html);
127}
128
129// An address that has done its job sends the browser back to the root page (303). The address bar
130// always shows / and reloading the page does not repeat the last tap.
131void goHome() {
132 server.sendHeader("Location", "/");
133 server.send(303);
134}
135
136// Every address has its own function; it runs when the browser asks for that address.
137void handleRoot() {
138 sendPage();
139}
140
141// Tapping a lamp stops the automatic cycle and flips only that lamp.
142void handleRed() {
143 stopAuto();
144 setLamps(!redOn, yellowOn, greenOn);
145 goHome();
146}
147
148void handleYellow() {
149 stopAuto();
150 setLamps(redOn, !yellowOn, greenOn);
151 goHome();
152}
153
154void handleGreen() {
155 stopAuto();
156 setLamps(redOn, yellowOn, !greenOn);
157 goHome();
158}
159
160// The auto button: starts the cycle at red when it is off, stops it and turns the lamps off when it
161// is on.
162void handleAuto() {
163 if (autoMode) {
164 stopAuto();
165 setLamps(false, false, false);
166 } else {
167 autoMode = true;
168 phase = 0;
169 phaseStart = millis();
170 Serial.println("Auto cycle started");
171 setLamps(true, false, false);
172 }
173 goHome();
174}
175
176void handleNotFound() {
177 server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
178}
179
180// The clock of the automatic cycle: moves on to the next lamp once the current one has had its
181// time. It never waits, it only looks at the time that has passed, so loop keeps turning and the
182// page keeps working.
183void runAuto() {
184 if (!autoMode || millis() - phaseStart < PHASE_MS[phase]) {
185 return;
186 }
187 phase = (phase + 1) % 3;
188 phaseStart = millis();
189 setLamps(phase == 0, phase == 2, phase == 1);
190}
191
192// Watches the connection: prints the IP address once connected and reports a drop. The ESP8266
193// rejoins a lost network by itself.
194void checkWifi() {
195 bool up = WiFi.status() == WL_CONNECTED;
196 if (up && !wifiUp) {
197 hintDone = true;
198 Serial.println("Wi-Fi connected");
199 Serial.print("Open in your browser: ");
200 Serial.print("http://");
201 Serial.println(WiFi.localIP());
202 } else if (!up && wifiUp) {
203 Serial.println("Wi-Fi lost. Reconnecting");
204 }
205 wifiUp = up;
206
207 if (!up && !hintDone && millis() > WIFI_HINT_MS) {
208 hintDone = true;
209 Serial.println("Could not join the Wi-Fi");
210 Serial.println("Check the network name and password");
211 Serial.println("The ESP8266 only sees 2.4 GHz networks");
212 }
213}
214
215void setup() {
216 Serial.begin(115200);
217 pinMode(PIN_RED, OUTPUT);
218 pinMode(PIN_YELLOW, OUTPUT);
219 pinMode(PIN_GREEN, OUTPUT);
220 digitalWrite(PIN_RED, LOW); // Start with the lamps off
221 digitalWrite(PIN_YELLOW, LOW);
222 digitalWrite(PIN_GREEN, LOW);
223 Serial.println();
224 Serial.println("Web traffic light");
225 if (strncmp(WIFI_SSID, "YOUR_", 5) == 0) {
226 Serial.println("Put your Wi-Fi name and password in the code");
227 }
228 Serial.println("Connecting to Wi-Fi");
229 // The board opens no network of its own, it joins yours
230 WiFi.mode(WIFI_STA);
231 WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
232
233 server.on("/", handleRoot);
234 server.on("/red", handleRed);
235 server.on("/yellow", handleYellow);
236 server.on("/green", handleGreen);
237 server.on("/auto", handleAuto);
238 server.onNotFound(handleNotFound);
239 server.begin();
240}
241
242// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
243void loop() {
244 checkWifi();
245 runAuto();
246 server.handleClient(); // Handles a waiting request
247}
248FAQ
How does the page keep working while the automatic cycle runs?
Because the code never waits with delay. On every pass loop checks with millis how long the current lamp has been on; if its time is not up, it moves straight on and handles a waiting web request. When the time is up it switches to the next lamp. So the board looks at the clock and at the browser thousands of times a second. With delay the board would be deaf to every tap for 3 seconds.
Why does the lamp on the page change a little later than the real LED?
The page has no script; during the cycle the browser asks for the page again every second and sees the state of that moment. The LED itself changes right on time. So the lamp on the screen can be up to one second behind, and the 1.5 second yellow may look short. Manual use has no lag: the tap reaches the board, the LED changes and the new page comes straight back.
Why did we use pins D5, D6 and D7?
These three pins sit side by side, have a GND pin right next to them and have no special job while the board starts. D3, D4 and D8 must be at a set level at boot; an LED on them can keep the board from starting. ESP8266 pins give 3.3 V and one pin should supply at most 12 mA; with 220 Ω each LED draws about 6 mA, so the board is comfortable even with all three on.
Can red and yellow be on together, as on a real traffic light?
By hand, yes: the lamps are independent, so tap red and then yellow. The automatic cycle is kept simple and lights one lamp at a time: red, green, yellow. Adding a fourth step where red and yellow shine together before green is the task in the Understand the code section; one more number in the times array and two changed lines are enough.
