E8-4ESP8266Beginner

ESP8266 Router-Free LED Control: the NodeMCU Opens Its Own Wi-Fi Network (Access Point)

Control an LED from your phone with no router and no internet. The NodeMCU V3 opens its own Wi-Fi network (BlueGrays-LED); join it with your phone and open 192.168.4.1 in the browser. The big button switches the LED on and off, three small buttons set the brightness to low, medium or full, and the bottom line shows how many devices are joined. This network has no internet: while the phone is on it, only the board's page opens.

0.0(0)
ESP8266 Router-Free LED Control: the NodeMCU Opens Its Own Wi-Fi Network (Access Point)
In the previous project the board joined your home router; here the board takes the router's place. The ESP8266 becomes an access point, broadcasts its own network and the phone connects straight to it. That way the same page works in the garden, in a car or anywhere without a router. You learn to give the network a name and a password, use the board's fixed address, count the joined devices and dim an LED in steps with PWM. Setup pages, robots in the field and offline remote controls are all built this way.

Video

Circuit Diagram

ESP8266 Router-Free LED Control: the NodeMCU Opens Its Own Wi-Fi Network (Access Point) - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   ESP8266 Router-Free LED Control: the NodeMCU Opens Its Own Wi-Fi Network (Access Point)
4// ─────────────────────────────────────────
5// The NodeMCU opens its own Wi-Fi network (an access point); no router or
6// internet needed. Join it with your phone, open 192.168.4.1 in the
7// browser and you can switch the LED on and off and set its brightness in
8// three steps. The page also shows how many devices are joined.
9//
10// Pins:
11//   D1 (GPIO5) -> 220 ohm resistor -> LED anode (long leg)
12//   GND        -> LED cathode (short leg)
13
14#include <ESP8266WiFi.h>
15#include <ESP8266WebServer.h>
16
17// ============ ACCESS POINT ============
18// The name and password of the network the board opens. The password is an EXAMPLE: write your own,
19// at least 8 characters.
20const char *const AP_SSID = "BlueGrays-LED";
21const char *const AP_PASSWORD = "12345678";
22
23// ============ PINS ============
24// D3, D4 and D8 have a special job while the board starts; the LED uses a spare pin such as D1.
25const uint8_t PIN_LED = D1;               // GPIO5
26
27// ============ BRIGHTNESS ============
28// analogWrite values: 0 is off, 255 is full. The eye tells dim light apart more easily, so the low
29// and medium steps are small numbers.
30const uint8_t LEVEL_LOW = 25;
31const uint8_t LEVEL_MID = 100;
32const uint8_t LEVEL_FULL = 255;
33
34// ============ PAGE TEXTS ============
35const char TEXT_TITLE[] = "Router-Free LED";
36const char TEXT_LED_ON[] = "LED is on";
37const char TEXT_LED_OFF[] = "LED is off";
38const char TEXT_TURN_ON[] = "TURN ON";
39const char TEXT_TURN_OFF[] = "TURN OFF";
40const char TEXT_BRIGHTNESS[] = "Brightness";
41const char TEXT_LOW[] = "Low";
42const char TEXT_MID[] = "Medium";
43const char TEXT_FULL[] = "Full";
44const char TEXT_DEVICES[] = "Connected devices";
45const char TEXT_NOT_FOUND[] = "Page not found";
46
47// ============ WEB PAGE ============
48// The fixed top of the page: UTF-8 encoding, a phone-friendly width, a reload every 5 seconds and
49// the looks (CSS).
50const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
51<meta name="viewport" content="width=device-width,initial-scale=1">
52<meta http-equiv="refresh" content="5;url=/"><title>ESP8266 LED</title>
53<style>
54body{margin:0;padding:32px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
55text-align:center}
56h1{font-size:26px;margin:0 0 8px}
57p{font-size:20px;color:#94a3b8;margin:0 0 24px}
58a{display:block;max-width:300px;margin:0 auto 32px;padding:40px 0;border-radius:28px;
59background:#334155;color:#f8fafc;font-size:32px;font-weight:bold;text-decoration:none}
60a.on{background:#facc15;color:#1f2937}
61div{display:flex;max-width:308px;margin:0 auto 32px}
62div a{flex:1;margin:0 4px;padding:18px 0;border-radius:16px;font-size:17px}
63</style></head><body>)rawliteral";
64
65ESP8266WebServer server(80);              // Port 80: the web default
66bool ledOn = false;
67uint8_t level = LEVEL_FULL;               // The chosen brightness
68uint8_t deviceCount = 0;                  // Devices joined to the board
69
70// Lights the LED at the chosen brightness or turns it off and reports it on the Serial port.
71// analogWrite switches the pin on and off very fast (PWM): the bigger the number, the brighter the
72// LED.
73void setLed(bool on) {
74  ledOn = on;
75  analogWrite(PIN_LED, on ? level : 0);
76  if (on) {
77    Serial.print("LED on, brightness: ");
78    Serial.println(level);
79  } else {
80    Serial.println("LED off");
81  }
82}
83
84// Adds one brightness button to the page; the chosen step is yellow while the LED is on.
85void addLevelButton(String &html, const char *address, const char *text, uint8_t value) {
86  html += (ledOn && level == value) ? "<a class=\"on\" href=\"" : "<a href=\"";
87  html += address;
88  html += "\">";
89  html += text;
90  html += "</a>";
91}
92
93// Builds the page for the current state and sends it to the browser: the on and off button, three
94// brightness buttons and the number of devices joined to the board.
95void sendPage() {
96  String html = PAGE_HEAD;
97  html += "<h1>";
98  html += TEXT_TITLE;
99  html += "</h1><p>";
100  html += ledOn ? TEXT_LED_ON : TEXT_LED_OFF;
101  html += "</p>";
102  html += ledOn ? "<a class=\"on\" href=\"/off\">" : "<a href=\"/on\">";
103  html += ledOn ? TEXT_TURN_OFF : TEXT_TURN_ON;
104  html += "</a><p>";
105  html += TEXT_BRIGHTNESS;
106  html += "</p><div>";
107  addLevelButton(html, "/low", TEXT_LOW, LEVEL_LOW);
108  addLevelButton(html, "/mid", TEXT_MID, LEVEL_MID);
109  addLevelButton(html, "/full", TEXT_FULL, LEVEL_FULL);
110  html += "</div><p>";
111  html += TEXT_DEVICES;
112  html += ": ";
113  html += deviceCount;
114  html += "</p></body></html>";
115  // The browser must not keep a copy of the page; every tap has to reach the board.
116  server.sendHeader("Cache-Control", "no-store");
117  server.send(200, "text/html; charset=utf-8", html);
118}
119
120// Every address has its own function; it runs when the browser asks for that address.
121void handleRoot() {
122  sendPage();
123}
124
125void handleOn() {
126  setLed(true);
127  sendPage();
128}
129
130void handleOff() {
131  setLed(false);
132  sendPage();
133}
134
135// Picking a brightness also turns the LED on.
136void setLevel(uint8_t value) {
137  level = value;
138  setLed(true);
139  sendPage();
140}
141
142void handleLow() {
143  setLevel(LEVEL_LOW);
144}
145
146void handleMid() {
147  setLevel(LEVEL_MID);
148}
149
150void handleFull() {
151  setLevel(LEVEL_FULL);
152}
153
154void handleNotFound() {
155  server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
156}
157
158// Prints the new count on the Serial port when a device joins or leaves the network.
159void checkDevices() {
160  uint8_t count = WiFi.softAPgetStationNum();
161  if (count != deviceCount) {
162    deviceCount = count;
163    Serial.print("Connected devices: ");
164    Serial.println(deviceCount);
165  }
166}
167
168void setup() {
169  Serial.begin(115200);
170  pinMode(PIN_LED, OUTPUT);
171  digitalWrite(PIN_LED, LOW);             // Start with the LED off
172  analogWriteRange(255);                  // Brightness range 0-255
173  Serial.println();
174  Serial.println("Router-free LED control");
175  if (strcmp(AP_PASSWORD, "12345678") == 0) {
176    Serial.println("Example password in use, change it");
177  }
178  // The board opens its own network, no router needed. softAP returns false if the password is
179  // shorter than 8 characters.
180  WiFi.mode(WIFI_AP);
181  if (WiFi.softAP(AP_SSID, AP_PASSWORD)) {
182    Serial.print("Network is up, join it with your phone: ");
183    Serial.println(AP_SSID);
184    Serial.print("Open in your browser: ");
185    Serial.print("http://");
186    Serial.println(WiFi.softAPIP());
187  } else {
188    Serial.println("Could not start the network");
189    Serial.println("The password needs at least 8 characters");
190  }
191
192  server.on("/", handleRoot);
193  server.on("/on", handleOn);
194  server.on("/off", handleOff);
195  server.on("/low", handleLow);
196  server.on("/mid", handleMid);
197  server.on("/full", handleFull);
198  server.onNotFound(handleNotFound);
199  server.begin();
200}
201
202// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
203void loop() {
204  checkDevices();
205  server.handleClient();                  // Handles a waiting request
206}
207

FAQ

How is this different from the web page LED project?

There the board joined your home router (station mode) and the router handed out its address. Here the board opens its own network (access point mode): no router is needed and the address is always 192.168.4.1. The price is that the phone has no internet while it is on this network. The page gained three brightness steps and a count of joined devices; for the brightness the pin is driven with analogWrite.

How far does the board's network reach?

The small antenna on the board covers roughly 30 to 40 metres in the open and 10 to 15 metres indoors through a wall or two. Concrete walls, metal boxes and a running microwave oven shorten the range. It helps to put the board up high and keep the antenna (the zigzag trace at the top end of the board) away from wires. If the phone walks out of range and drops off, it rejoins once it is close again.

How many devices can join at the same time?

Four by default. The fifth value of softAP raises that to 8 at most: WiFi.softAP(AP_SSID, AP_PASSWORD, 1, false, 8). Everyone who is joined sees the same page and can control the LED; a change made on one phone shows up on the others within 5 seconds, when the page reloads itself. The number on the page counts devices joined to the network, not the ones that opened the page.

Why can't my phone reach the internet while it is on this network?

Because the board's network is not connected to the internet; it only links the board and the phone. The one place the phone can open on it is the board's page. When you are done, go back to your home network in the Wi-Fi settings. Some phones leave a network without internet on their own; see the troubleshooting section. If you need internet too, the previous project, which joins the router, fits better.