ESP8266 Web Light Meter: Measure the Room Light with an LDR and See It as a Percentage on Your Phone
Cover the LDR with your hand and the number on your phone drops; shine a light on it and it rises. The NodeMCU V3 joins your home Wi-Fi, measures the room light with an LDR and shows it on a page as a percentage. The page never reloads: a small script asks the board for the value twice a second and updates the number and the bar. The circuit is just an LDR and a 10 kΩ resistor on A0, the only analog input of the board. No app needed. The ESP8266 only joins 2.4 GHz networks.

Video
Circuit Diagram

Source Code
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// ESP8266 Web Light Meter: Measure the Room Light with an LDR and See It as a Percentage on Your Phone
4// ─────────────────────────────────────────
5// The NodeMCU joins your home Wi-Fi and measures the light in the room.
6// Open the board's IP address in the browser of a phone on the same
7// network: the page shows the light level as a percentage. Cover the LDR
8// with your hand and the number drops; shine a light on it and it rises.
9// The page asks the board for the value twice a second.
10//
11// Pins:
12// 3V3 -> one leg of the LDR
13// A0 -> the other leg of the LDR + 10k resistor
14// GND -> the other leg of the 10k resistor
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// ============ MEASUREMENT ============
27// A0 is the only analog input of the board; the NodeMCU reads 0 to 3.3 V as 0 to 1023. Reading A0
28// on every pass disturbs the Wi-Fi, so the readings are spaced out.
29const unsigned long READ_MS = 250; // ms
30
31// ============ PAGE TEXTS ============
32const char TEXT_TITLE[] = "Light Meter";
33const char TEXT_NOT_FOUND[] = "Page not found";
34
35// ============ WEB PAGE ============
36// The fixed top of the page: UTF-8 encoding, a phone-friendly width and the looks (CSS).
37const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
38<meta name="viewport" content="width=device-width,initial-scale=1"><title>ESP8266</title>
39<style>
40body{margin:0;padding:28px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
41text-align:center}
42h1{font-size:26px;margin:0 0 28px}
43p{font-size:84px;font-weight:bold;margin:0 0 28px;color:#facc15}
44div{max-width:300px;height:28px;margin:0 auto;border-radius:14px;background:#334155;overflow:hidden}
45i{display:block;height:28px;background:#facc15}
46</style></head><body>)rawliteral";
47
48// The script of the page: twice a second it asks the board for /value, writes the percentage it
49// gets and fills the bar that far.
50const char PAGE_SCRIPT[] = R"rawliteral(<script>
51setInterval(function(){
52fetch('/value').then(function(r){return r.text()}).then(function(t){
53document.getElementById('n').textContent=t+'%';
54document.getElementById('b').style.width=t+'%';
55})},500);
56</script></body></html>)rawliteral";
57
58ESP8266WebServer server(80); // Port 80: the web default
59int lightPercent = 0;
60unsigned long lastRead = 0;
61bool wifiUp = false;
62bool hintDone = false;
63
64// Measures the light: turns the A0 value (0 to 1023) into a percentage. The more light the LDR
65// gets, the lower its resistance and the higher the voltage on A0.
66void readLight() {
67 if (millis() - lastRead < READ_MS) {
68 return;
69 }
70 lastRead = millis();
71 int percent = map(analogRead(A0), 0, 1023, 0, 100);
72 if (percent != lightPercent) {
73 lightPercent = percent;
74 Serial.print("Light: ");
75 Serial.print(lightPercent);
76 Serial.println("%");
77 }
78}
79
80// Builds the page with the current value and sends it to the browser; the script keeps it up to
81// date after that.
82void sendPage() {
83 String html = PAGE_HEAD;
84 html += "<h1>";
85 html += TEXT_TITLE;
86 html += "</h1><p id=\"n\">";
87 html += lightPercent;
88 html += "%</p><div><i id=\"b\" style=\"width:";
89 html += lightPercent;
90 html += "%\"></i></div>";
91 html += PAGE_SCRIPT;
92 // The browser must not keep a copy of the page; every tap has to reach the board.
93 server.sendHeader("Cache-Control", "no-store");
94 server.send(200, "text/html; charset=utf-8", html);
95}
96
97// Every address has its own function; it runs when the browser asks for that address.
98void handleRoot() {
99 sendPage();
100}
101
102// The script asks for this address. The answer is a short text, the page stays where it is.
103void handleValue() {
104 String text = String(lightPercent);
105 server.sendHeader("Cache-Control", "no-store");
106 server.send(200, "text/plain", text);
107}
108
109void handleNotFound() {
110 server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
111}
112
113// Watches the connection: prints the IP address once connected and reports a drop. The ESP8266
114// rejoins a lost network by itself.
115void checkWifi() {
116 bool up = WiFi.status() == WL_CONNECTED;
117 if (up && !wifiUp) {
118 hintDone = true;
119 Serial.println("Wi-Fi connected");
120 Serial.print("Open in your browser: ");
121 Serial.print("http://");
122 Serial.println(WiFi.localIP());
123 } else if (!up && wifiUp) {
124 Serial.println("Wi-Fi lost. Reconnecting");
125 }
126 wifiUp = up;
127
128 if (!up && !hintDone && millis() > WIFI_HINT_MS) {
129 hintDone = true;
130 Serial.println("Could not join the Wi-Fi");
131 Serial.println("Check the network name and password");
132 Serial.println("The ESP8266 only sees 2.4 GHz networks");
133 }
134}
135
136void setup() {
137 Serial.begin(115200);
138 Serial.println();
139 Serial.println("Web light meter");
140 if (strncmp(WIFI_SSID, "YOUR_", 5) == 0) {
141 Serial.println("Put your Wi-Fi name and password in the code");
142 }
143 Serial.println("Connecting to Wi-Fi");
144 // The board opens no network of its own, it joins yours
145 WiFi.mode(WIFI_STA);
146 WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
147
148 server.on("/", handleRoot);
149 server.on("/value", handleValue);
150 server.onNotFound(handleNotFound);
151 server.begin();
152}
153
154// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
155void loop() {
156 checkWifi();
157 readLight();
158 server.handleClient(); // Handles a waiting request
159}
160FAQ
What is an LDR and how does it work?
An LDR is a part whose resistance changes with the light that falls on it. In the dark its resistance is very high (hundreds of thousands of ohms), in bright light it drops to a few hundred ohms. The board cannot measure resistance directly, so the LDR is wired in series with a 10 kΩ resistor and the voltage of the middle point is read. More light means a higher voltage.
Is this percentage a lux value?
No. The number shows where the voltage on A0 sits between 0 and 3.3 V; it is not a real unit of light. Two different LDRs in the same room may give slightly different numbers. It is still good enough to compare: it easily tells night from day, an open curtain from a closed one and whether the lamp is on.
Why a 10 kΩ resistor?
The resistor splits the voltage together with the LDR. 10 kΩ is close to the resistance of the LDR in room light, so the number sticks neither to the bottom nor to the top and changes are easy to see. For a very dim place try 47 kΩ or 100 kΩ: the number moves more on the dark side. Without the resistor the number only drops in deep darkness and the measurement is useless.
Why does the page update by itself?
A small script inside the page asks the board for /value every half second. The board sends only the number; the script writes it on the screen and fills the bar that far. The whole page is never loaded again, so the screen does not flicker and the board has little work. When you close the page, the questions stop too.
