E8-6ESP8266Beginner

ESP8266 LED Brightness with a Web Slider: PWM Dimming from Your Phone with a NodeMCU

Move a slider in your phone's browser and let the LED follow your finger. The NodeMCU V3 joins your home Wi-Fi and serves a page with a single slider: 0% is off, 100% is full brightness. The board sets the brightness with PWM: it switches the pin on and off very fast, and the longer the on share, the brighter the LED looks. Every move sends the board a small request and the page never reloads. The ESP8266 only joins 2.4 GHz networks.

0.0(0)
ESP8266 LED Brightness with a Web Slider: PWM Dimming from Your Phone with a NodeMCU
The step after an on and off button: this time the web page sends the board a number. You learn how to add the slider value to the end of the address, how the board reads that number, keeps it within limits and turns it into brightness. You also meet a small script that sends requests in the background without reloading the page. The same method drives fan speed, motor speed, servo angle and anything else you set with a number from your phone.

Video

Circuit Diagram

ESP8266 LED Brightness with a Web Slider: PWM Dimming from Your Phone with a NodeMCU - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   ESP8266 LED Brightness with a Web Slider: PWM Dimming from Your Phone with a NodeMCU
4// ─────────────────────────────────────────
5// The NodeMCU joins your home Wi-Fi and serves a page with a single
6// slider. Open the board's IP address in the browser of a phone on the
7// same network and move the slider: the LED follows your finger. The board
8// sets the brightness with PWM: it switches the pin on and off very fast,
9// and the longer the on share, the brighter the LED looks.
10//
11// Pins:
12//   D5 (GPIO14) -> 220 ohm resistor -> LED anode (long leg)
13//   GND         -> LED cathode (short leg, minus rail)
14
15#include <ESP8266WiFi.h>
16#include <ESP8266WebServer.h>
17
18// ============ WI-FI NETWORK ============
19// Write the name and password of your own network inside the quotes. The ESP8266 only joins 2.4 GHz
20// networks.
21const char *const WIFI_SSID = "YOUR_WIFI_NAME";
22const char *const WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
23const unsigned long WIFI_HINT_MS = 20000; // Time until the hint (ms)
24
25// ============ PINS ============
26// D3, D4 and D8 have a special job while the board starts; the LED uses the spare pin D5.
27const uint8_t PIN_LED = D5;               // GPIO14
28
29// ============ BRIGHTNESS ============
30// The top PWM value. Core 3.x counts to 255 by default, older cores to 1023; setup fixes the range
31// so the code works the same on both.
32const int PWM_MAX = 255;
33
34// ============ PAGE TEXTS ============
35const char TEXT_TITLE[] = "LED Brightness";
36const char TEXT_NOT_FOUND[] = "Page not found";
37
38// ============ WEB PAGE ============
39// The fixed top of the page: UTF-8 encoding, a phone-friendly width and the looks (CSS).
40const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
41<meta name="viewport" content="width=device-width,initial-scale=1"><title>ESP8266</title>
42<style>
43body{margin:0;padding:28px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
44text-align:center}
45h1{font-size:26px;margin:0 0 28px}
46p{font-size:72px;font-weight:bold;margin:0 0 28px;color:#facc15}
47input{width:100%;max-width:320px;height:56px;accent-color:#facc15}
48</style></head><body>)rawliteral";
49
50// The script of the page: every slider move shows the number and asks the board for /set?v=NUMBER.
51// While one request is on its way it only remembers the newest value and sends it next, so the
52// board is never flooded.
53const char PAGE_SCRIPT[] = R"rawliteral(<script>
54var busy=false,next=-1;
55function send(v){
56document.getElementById('p').textContent=v+'%';
57if(busy){next=v;return}
58busy=true;
59fetch('/set?v='+v).then(done,done);
60}
61function done(){busy=false;if(next>=0){var v=next;next=-1;send(v)}}
62</script></body></html>)rawliteral";
63
64ESP8266WebServer server(80);              // Port 80: the web default
65int percent = 0;
66bool wifiUp = false;
67bool hintDone = false;
68
69// Turns the percentage (0-100) into a PWM value and writes it to the LED pin.
70void setBrightness(int value) {
71  percent = constrain(value, 0, 100);
72  analogWrite(PIN_LED, map(percent, 0, 100, 0, PWM_MAX));
73  Serial.print("Brightness: ");
74  Serial.print(percent);
75  Serial.println("%");
76}
77
78// Builds the page for the current brightness and sends it to the browser: the number and the
79// slider.
80void sendPage() {
81  String html = PAGE_HEAD;
82  html += "<h1>";
83  html += TEXT_TITLE;
84  html += "</h1><p id=\"p\">";
85  html += percent;
86  html += "%</p><input type=\"range\" min=\"0\" max=\"100\" value=\"";
87  html += percent;
88  html += "\" oninput=\"send(this.value)\">";
89  html += PAGE_SCRIPT;
90  // The browser must not keep a copy of the page; every tap has to reach the board.
91  server.sendHeader("Cache-Control", "no-store");
92  server.send(200, "text/html; charset=utf-8", html);
93}
94
95// Every address has its own function; it runs when the browser asks for that address.
96void handleRoot() {
97  sendPage();
98}
99
100// The slider asks for this address: v is the new percentage. The answer is just the number, the
101// page stays where it is.
102void handleSet() {
103  if (server.hasArg("v")) {
104    setBrightness(server.arg("v").toInt());
105  }
106  server.sendHeader("Cache-Control", "no-store");
107  server.send(200, "text/plain", String(percent));
108}
109
110void handleNotFound() {
111  server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
112}
113
114// Watches the connection: prints the IP address once connected and reports a drop. The ESP8266
115// rejoins a lost network by itself.
116void checkWifi() {
117  bool up = WiFi.status() == WL_CONNECTED;
118  if (up && !wifiUp) {
119    hintDone = true;
120    Serial.println("Wi-Fi connected");
121    Serial.print("Open in your browser: ");
122    Serial.print("http://");
123    Serial.println(WiFi.localIP());
124  } else if (!up && wifiUp) {
125    Serial.println("Wi-Fi lost. Reconnecting");
126  }
127  wifiUp = up;
128
129  if (!up && !hintDone && millis() > WIFI_HINT_MS) {
130    hintDone = true;
131    Serial.println("Could not join the Wi-Fi");
132    Serial.println("Check the network name and password");
133    Serial.println("The ESP8266 only sees 2.4 GHz networks");
134  }
135}
136
137void setup() {
138  Serial.begin(115200);
139  pinMode(PIN_LED, OUTPUT);
140  analogWriteRange(PWM_MAX);
141  digitalWrite(PIN_LED, LOW);             // Start with the LED off
142  Serial.println();
143  Serial.println("Slider LED");
144  if (strncmp(WIFI_SSID, "YOUR_", 5) == 0) {
145    Serial.println("Put your Wi-Fi name and password in the code");
146  }
147  Serial.println("Connecting to Wi-Fi");
148  // The board opens no network of its own, it joins yours
149  WiFi.mode(WIFI_STA);
150  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
151
152  server.on("/", handleRoot);
153  server.on("/set", handleSet);
154  server.onNotFound(handleNotFound);
155  server.begin();
156}
157
158// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
159void loop() {
160  checkWifi();
161  server.handleClient();                  // Handles a waiting request
162}
163

FAQ

What is PWM and how does it dim the LED?

A pin cannot be half on: it gives either 3.3 V or 0 V. PWM switches the pin on and off about a thousand times a second; the eye cannot follow that and only sees the average. With a quarter on share the LED looks dim, with a full one it looks fully bright. analogWrite takes that share as a number from 0 to 255; the code turns the percentage from the page into that range.

Is the top value for analogWrite 255 or 1023?

In the 3.x versions of the ESP8266 core the range is 0 to 255 by default; older versions used 0 to 1023. That is why numbers from old examples can give a different result on a new core. This code fixes the range at 255 with analogWriteRange in setup, so it works the same whichever version you have installed.

Does moving the slider fast flood the board with requests?

No, because the script on the page sends one request at a time. If the slider keeps moving while a request is on its way, the script only remembers the newest value and sends it when the answer arrives; the values in between are skipped. The LED follows your finger in small steps and the value at the moment you let go always reaches the board.

Why does the brightness rise so fast at low percentages?

The eye does not see light in a straight line: small changes look big in the dark and big changes look small when it is bright. So 0 to 20 feels like a big jump while 80 to 100 looks almost the same. For a more even feel you can use the square of the percentage; that is the task in the Understand the code section.