Fall ResetAmazon USFall reset deals: check better picks before checkoutAmazon US: today's deals, useful picks and quick comparisons.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowFall ResetAmazon USWork and home upgrades are worth comparing todayAmazon US: today's deals, useful picks and quick comparisons.See Picks×
Skip to content
Blog

NodeMCU ESP8266 LDR IoT Project: Wiring, Reading and Sending Light Data

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Connect an LDR to a NodeMCU ESP8266 through a voltage divider, read its changing output with analogRead(A0), then send that relative light reading over Wi-Fi to a local page or an IoT dashboard. The key safety check comes first: the bare ESP8266 ADC is specified for 0–1.0 V, while A0 scaling varies between development boards. Verify your board’s input range before wiring a divider powered from 3.3 V.

This project produces a relative light measurement, not a lux reading. You can use it for experiments or a calibrated dark/light threshold; meaningful lux estimates require calibration against a reference.

How the project works

An LDR (light-dependent resistor, also called a photoresistor) changes resistance as the light falling on it changes. It does not generate a useful voltage by itself. Pair it with a fixed resistor to form a voltage divider, connect the divider junction to A0, and the ESP8266’s ADC converts the resulting voltage into a number. The board can then transmit that value over Wi-Fi.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Light → LDR resistance changes → voltage divider → A0 reading → Wi-Fi → page or dashboard

“NodeMCU” commonly refers to ESP8266 development boards, but it is not one uniform hardware specification. Board makers and clones may differ in the A0 divider, regulator, USB-to-serial chip and pin layout. The project below assumes an ESP8266 NodeMCU-style board programmed with the Arduino IDE.

#1 Best Overall
NodeMCU ESP8266 Development Board with 0.96 Inch OLED Display, CH340 Driver, ESP-12E WiFi Wireless Module, and Micro USB Works Great for Arduino IDE/Micropython Programming (Pin Header Soldered)
  • The ESP8266 NodeMCU board has all the features of the traditional ESP8266 module,with the same exact size and peripheral ports,offers seamless integration with a 0.96-inch OLED display, eliminating the need for frustrating wires and breadboards.Display features a high-resolution 128x64 with SSD1306 driver and is compatible with I2C,SPI interfaces. Plus,It uses Micro usb cable to connect. Say goodbye to messy setups and hello to hassle-free electronics with the ESP8266 NodeMCU board
  • This board uses I2C to connect to an OLED display via the SDA (D6 / GPIO12) and SCL (D5 / GPIO14) pins. With this board,it's easy to display a variety of information and data
  • To install the new version driver for CH340,simply search for the keywords "CH340 Driver" on Google.com or Bing.com and follow the installation instructions provided.Recommended for Win10 Operating System
  • ESP8266 NodeMCU board is equipped with ESP-12E module,which contains the Tensilica Xtensa 32-bit LX106 RISC microprocessor powering the ESP8266 chip. This microprocessor supports RTOS and operates at a clock frequency that can be adjusted between 80MHz and 160 MHz. It also boasts 128 KB of RAM and 4MB of Flash memory, providing ample storage for data and programs. With its high processing power, built-in Wi-Fi, and Deep Sleep Operating features, It's is an excellent choice for IoT projects
  • This board is an outstanding option for various Internet of Things (IoT) projects. It can be used to display network connection status,monitor information, power levels, and other relevant data. Additionally, it's suitable for building Internet Weather Stations, News Stations, Clocks, and Other similar applications

Parts and setup

  • ESP8266 NodeMCU development board, preferably with documentation for its A0 input range
  • LDR/photoresistor
  • 10 kΩ fixed resistor as a starting value
  • Breadboard, jumper wires and a data-capable Micro-USB cable
  • Computer with the Arduino IDE and ESP8266 board support
  • Optional: multimeter to check the A0 voltage; Blynk account or a local network device for a dashboard

A 10 kΩ resistor is a practical starting point, not a universal optimum. The divider is most responsive when the fixed resistor is in the same general range as the LDR’s resistance under the lighting conditions you care about. LDR resistance varies widely with illumination and between components.

Check A0’s voltage limit before wiring

The ESP8266 Arduino core documents the bare ESP8266 ADC input range as 0–1.0 V. Some NodeMCU-style boards add an onboard voltage divider so a higher voltage can be applied at the board’s A0 pin, but the scaling is board-specific. Do not assume that a board powered at 3.3 V can safely accept 3.3 V on A0. Consult the board documentation or measure the pin’s input range before connecting a 3.3 V-powered divider. See the ESP8266 ADC reference and core documentation for analogRead.

If you cannot confirm the board’s A0 range, do not connect a divider output that could exceed the bare ADC’s 1.0 V limit. Measure the junction voltage with a multimeter and adapt the circuit to the verified limit. Never connect a 5 V sensor output directly to A0.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wire the LDR voltage divider

For the arrangement below, the LDR is above the A0 junction and the fixed resistor is below it. Connect the divider supply to the board’s 3V3 pin, not a 5 V supply.

NodeMCU 3V3 ───── LDR ─────┬──── A0
                            │
                          10 kΩ
                            │
NodeMCU GND ────────────────┘

The divider relationship is Vout = Vin × Rbottom / (Rtop + Rbottom). Here, Rtop is the LDR, Rbottom is the fixed resistor, and Vout is the A0 junction voltage. As light increases, LDR resistance generally falls, so the junction voltage and ADC reading generally rise.

You can swap the LDR and fixed resistor:

NodeMCU 3V3 ───── 10 kΩ ───┬──── A0
                           │
                          LDR
                           │
NodeMCU GND ──────────────┘

This orientation generally makes the ADC reading fall as light increases. It is not a fault; choose the orientation that makes the behavior easiest to interpret.

Rank #2
Hosyond 3Pcs ESP8266 ESP-12E CP2102 NodeMCU Lua Wireless Module Development Board for Arduino IDE/Micropython
  • Not only it is easy to program for this controller by using the CP2102-USB interface,but also unnecessary to press the flash and reset buttons before each flash operation.
  • NodeMcu is an open source Lua based firmware for the ESP8266, ultra low cost wireless modules, development boards for rapid prototyping, integrated with ESP8266 chips.
  • The ESP8266 has powerful on-board processing and storage capabilities, and can be integrated with sensors and other application-specific devices through its GPIOs.
  • It is compatible with Arduino IDE,works great with the latest Mongoose IoT/Micropython.
  • Modern Internet development tools can use the built-in API to instantly put your idea on the fast track.

Install ESP8266 board support and choose the board

Follow the current ESP8266 Arduino core installation instructions; IDE menus and package versions can change. A common Arduino IDE route is to add https://arduino.esp8266.com/stable/package_esp8266com_index.json under File → Preferences → Additional Boards Manager URLs, then open Tools → Board → Boards Manager, search for esp8266, and install the ESP8266 Community package.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a typical board, select Tools → Board → ESP8266 Boards → NodeMCU 1.0 (ESP-12E Module), then choose the serial port for the connected board. Your board may need a different selection or a USB driver. If upload fails, try a known-good data cable, check the port and board selection, close the Serial Monitor during upload, and consult the board’s instructions for using its Flash/BOOT button.

First test: read the sensor locally

Validate the circuit before adding Wi-Fi or a cloud service. Upload this diagnostic sketch:

const int LDR_PIN = A0;

void setup() {
  Serial.begin(115200);
  delay(500);
}

void loop() {
  int raw = analogRead(LDR_PIN);

  Serial.print("LDR raw value: ");
  Serial.println(raw);

  delay(500);
}

Open the Serial Monitor at 115200 baud. The number should change when you cover the LDR or shine a lamp on it. The direction depends on which component is above the divider junction. The ESP8266 exposes one user-accessible ADC channel; analogRead(A0) reads that input. Common NodeMCU sketches treat the returned value as a roughly 0–1023 count, but the voltage represented by those counts depends on the ADC and board-level scaling. Do not infer a safe input voltage from the number alone.

If you need voltage, use float voltage = raw * ADC_MAX_VOLTAGE / 1023.0; only after establishing the effective input range. For example, use 1.0 as ADC_MAX_VOLTAGE for a confirmed bare 0–1.0 V ADC range. Use a different value only when your board’s scaling is known. A raw reading is usually enough for relative thresholds and avoids pretending the LDR is a calibrated instrument.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Smooth readings and set a threshold

Small changes in readings can come from light flicker, wiring, power noise or the surrounding environment. A short average can make a display steadier:

Rank #3
HiLetgo 3pcs ESP8266 NodeMCU CP2102 ESP-12E Development Board Open Source Serial Module Works Great for Arduino IDE/Micropython (Large)
  • Built-in Micro-USB, with flash and reset switches, easy to program
  • Arduino compatible, works great with the latest Arduino IDE/Mongoose IoT/Micropython
  • Data download access to the website: http://www;nodemcu;com
const int LDR_PIN = A0;
const int SAMPLES = 10;

int readSmoothedLdr() {
  long total = 0;

  for (int i = 0; i < SAMPLES; i++) {
    total += analogRead(LDR_PIN);
    delay(5);
  }

  return total / SAMPLES;
}

void setup() {
  Serial.begin(115200);
}

void loop() {
  int reading = readSmoothedLdr();
  Serial.println(reading);
  delay(500);
}

Averaging reduces short-term variation but adds measurement time and can make a sudden lighting change appear slower. For a lamp controlled by a threshold, use hysteresis so the output does not chatter when the reading hovers near one cutoff. The example assumes a reading that falls in darkness; reverse the comparisons if your divider orientation behaves oppositely.

const int ON_THRESHOLD  = 350;  // Example only: calibrate for your circuit
const int OFF_THRESHOLD = 450;
bool lampOn = false;

void updateLamp(int lightValue) {
  if (!lampOn && lightValue < ON_THRESHOLD) {
    lampOn = true;
    digitalWrite(LED_BUILTIN, LOW);  // Many ESP8266 boards use an active-low LED
  } else if (lampOn && lightValue > OFF_THRESHOLD) {
    lampOn = false;
    digitalWrite(LED_BUILTIN, HIGH);
  }
}

These threshold numbers are illustrative, not portable settings. Test the actual divider in the intended location and choose cutoffs with enough separation to avoid repeated switching.

Connect the NodeMCU to Wi-Fi

Once the sensor test works, verify network access separately. Replace the placeholders with your network credentials:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#include <ESP8266WiFi.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.print("Connected. IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {}

If it does not connect, check the spelling and capitalization of the SSID and password, move the board nearer the router, and confirm the network configuration is compatible. ESP8266 boards use 2.4 GHz Wi-Fi; a 5 GHz-only network will not work. Captive portals and restrictive router settings can also prevent connection. This example waits indefinitely, which is fine for a quick test but not resilient device firmware; a deployed device should use a timeout and a reconnection strategy.

Display readings on a local web page

A local web server is a useful first network result: it avoids a cloud account and lets another device on the same local network view the current reading.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const int LDR_PIN = A0;
ESP8266WebServer server(80);

void handleRoot() {
  int raw = analogRead(LDR_PIN);
  String page;
  page += "<!doctype html><html><head>";
  page += "<meta name='viewport' content='width=device-width,initial-scale=1'>";
  page += "<title>NodeMCU Light Monitor</title></head><body>";
  page += "<h1>NodeMCU LDR Monitor</h1>";
  page += "<p>Raw ADC reading: " + String(raw) + "</p>";
  page += "</body></html>";
  server.send(200, "text/html", page);
}

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println(WiFi.localIP());
  server.on("/", handleRoot);
  server.begin();
}

void loop() {
  server.handleClient();
}

Open the IP address printed in the Serial Monitor from a browser on the same network. It is a private local-network address, not automatically a public internet URL. Do not expose this simple, unauthenticated example to the public internet through port forwarding.

Rank #4
HiLetgo 2pcs ESP8266 NodeMCU CP2102 ESP-12E Development Board (Wi-Fi, USB) - Arduino Compatible, 1MB RAM, 80MHz CPU, 1M Flash, 2 Boards
  • ESP8266 CP2102 NodeMCU LUA ESP-12E WIFI Serial Wireless Module
  • Built-in Micro-USB, with flash and reset switches, easy to program
  • Arduino compatible, works great with the latest Arduino IDE/Mongoose IoT/Micropython
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Send readings to Blynk

For a beginner-friendly cloud dashboard, Blynk supports ESP8266 and NodeMCU-class boards. Follow its current supported boards documentation and code preparation guide; current platform terminology and setup may differ from older examples.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Create a Blynk template and device, then copy the template ID, template name and device authentication token into the sketch.
  2. Create a numeric Datastream on virtual pin V0.
  3. Add a value display or chart widget to the dashboard and connect it to that Datastream.
  4. Install the Blynk library, upload the sketch, and confirm the device is online.
  5. Check the Serial Monitor and dashboard for readings before changing the update interval.

This example averages eight readings and sends one value per second. It transmits a relative ADC count, not lux. Replace every placeholder, and do not publish your Wi-Fi password or authentication token.

#define BLYNK_TEMPLATE_ID "YOUR_TEMPLATE_ID"
#define BLYNK_TEMPLATE_NAME "NodeMCU LDR Monitor"
#define BLYNK_AUTH_TOKEN "YOUR_AUTH_TOKEN"

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char ssid[] = "YOUR_WIFI_NAME";
char pass[] = "YOUR_WIFI_PASSWORD";
const int LDR_PIN = A0;
const int SAMPLE_COUNT = 8;
BlynkTimer timer;

int readLdr() {
  long total = 0;
  for (int i = 0; i < SAMPLE_COUNT; i++) {
    total += analogRead(LDR_PIN);
    delay(3);
  }
  return total / SAMPLE_COUNT;
}

void publishLdr() {
  int value = readLdr();
  Serial.print("LDR reading: ");
  Serial.println(value);
  if (Blynk.connected()) {
    Blynk.virtualWrite(V0, value);
  }
}

void setup() {
  Serial.begin(115200);
  delay(500);
  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
  timer.setInterval(1000L, publishLdr);
}

void loop() {
  Blynk.run();
  timer.run();
}

The timer avoids sending continuously, but Blynk.begin() can block during connection attempts. A production device should manage Wi-Fi and cloud reconnection deliberately, keep local sensing useful during an outage, and decide whether to buffer or discard missed readings. Realtime protocols such as Blynk or MQTT keep a connection open; periodic HTTPS reporting can suit some intermittent or low-bandwidth designs. See Blynk’s sensor-data guide, which also recommends verifying sensor output locally before dashboard setup.

Interpret and calibrate the result

  • Raw ADC reading: Useful for relative comparisons and thresholds on the same board and circuit.
  • Voltage: Calculate only when the board’s effective A0 range is known. The board’s onboard divider, if present, matters.
  • Lux: Do not label a raw ADC count as lux. An LDR’s response is nonlinear and varies with the part, resistor, geometry and lighting.

To create an approximate lux estimate, record the ADC count and calculated voltage under multiple lighting conditions while measuring those same conditions with a calibrated lux meter or trusted reference. Fit a curve or lookup table, and document the LDR part, resistor, placement and calibration environment. Without that work, call the value a “relative light level,” “ambient-light index,” or “ADC reading.”

Troubleshooting

Symptom Likely causes What to check
A0 stays at zero Junction shorted to ground, incomplete divider, wrong pin, or a board/ADC fault Disconnect power, rebuild the divider, check continuity from the junction to A0, measure the junction voltage, and run the sensor-only sketch.
A0 stays near maximum A0 tied to 3.3 V, divider voltage beyond the effective range, or incorrect LDR wiring Measure the junction voltage, verify board scaling, and correct the divider before reconnecting. Never apply a 5 V output.
Reading moves the “wrong” way The LDR and fixed resistor are in the opposite orientation from the expected trend Swap their positions or invert the software value after confirming the actual ADC range and readings.
Reading is noisy Long wires, poor breadboard contact, power noise, flickering lights, or a high-impedance divider Shorten wires, improve connections, average samples, and consider a small capacitor across the fixed resistor. A capacitor steadies the signal but slows response.
Upload fails Wrong board or port, charge-only USB cable, driver issue, or boot-mode requirement Check the board and port, use a data cable, close the Serial Monitor, and follow the board’s Flash/BOOT procedure.
Wi-Fi does not connect Incorrect credentials, out-of-range signal, 5 GHz-only network, captive portal, or router policy Check SSID/password, test near a compatible 2.4 GHz network, and add status/timeout diagnostics.
Blynk device is online but the dashboard is blank Wrong token or template details, mismatched virtual pin, timer not running, or missing Blynk.run() Match the configured Datastream and code pin, verify the device status, and confirm sensor readings in Serial Monitor first.

When to use another sensor or platform

A bare LDR and resistor are inexpensive and instructive, but not the best choice for every light-monitoring job. A comparator-based LDR module can provide a digital dark/light threshold, often adjustable with a potentiometer; its analog output, if used, still needs A0 voltage-range verification. For more repeatable illuminance measurement, a digital ambient-light sensor such as the BH1750FVI family is a more appropriate starting point than an uncalibrated photoresistor.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Blynk is a quick path to a hosted dashboard. MQTT with a broker such as Mosquitto, plus Home Assistant or Node-RED, offers more local control and interoperability but requires more setup and maintenance. A local web page is simplest when viewing data only on the home network. The ESP8266 has one user-accessible ADC channel, so multiple analog sensors require an external ADC or multiplexer, or a different microcontroller.

For battery operation, account for both the continuously connected Wi-Fi radio and current through the LDR divider. An always-on USB demonstration is simpler; a battery design needs a power budget and a reporting strategy suited to intermittent connections, such as carefully designed deep sleep.

Quick Recap

Bestseller No. 2
Hosyond 3Pcs ESP8266 ESP-12E CP2102 NodeMCU Lua Wireless Module Development Board for Arduino IDE/Micropython
Hosyond 3Pcs ESP8266 ESP-12E CP2102 NodeMCU Lua Wireless Module Development Board for Arduino IDE/Micropython
It is compatible with Arduino IDE,works great with the latest Mongoose IoT/Micropython.
$13.99
Bestseller No. 3
HiLetgo 3pcs ESP8266 NodeMCU CP2102 ESP-12E Development Board Open Source Serial Module Works Great for Arduino IDE/Micropython (Large)
HiLetgo 3pcs ESP8266 NodeMCU CP2102 ESP-12E Development Board Open Source Serial Module Works Great for Arduino IDE/Micropython (Large)
Built-in Micro-USB, with flash and reset switches, easy to program; Arduino compatible, works great with the latest Arduino IDE/Mongoose IoT/Micropython
$16.39
Bestseller No. 4
HiLetgo 2pcs ESP8266 NodeMCU CP2102 ESP-12E Development Board (Wi-Fi, USB) - Arduino Compatible, 1MB RAM, 80MHz CPU, 1M Flash, 2 Boards
HiLetgo 2pcs ESP8266 NodeMCU CP2102 ESP-12E Development Board (Wi-Fi, USB) - Arduino Compatible, 1MB RAM, 80MHz CPU, 1M Flash, 2 Boards
ESP8266 CP2102 NodeMCU LUA ESP-12E WIFI Serial Wireless Module; Built-in Micro-USB, with flash and reset switches, easy to program
$12.69

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.