ESP8266 - LDR Module
This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://newbiely.com/tutorials/esp8266/esp8266-ldr-module
The LDR light sensor module detects light two ways: a digital HIGH/LOW signal on its DO pin, and a variable analog signal on its AO pin. This guide connects the module to an ESP8266 and shows how to read both outputs, so you can tell whether it is light or dark, or measure how bright the surroundings are.
You can later use this to switch an LED or, through a relay, a light bulb when darkness is detected.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- ESP8266 NodeMCU ESP-12F
- ESP8266 D1 Mini NodeMCU ESP-12F
- ESP8266 NodeMCU ESP-12E (Uno-form)
- Micro USB Cable
- ESP8266 NodeMCU ESP-12F (SMD-form)
- USB Cable Type-A to Type-C (for USB-A PC)
- USB Cable Type-C to Type-C (for USB-C PC)
- LDR Light Sensor Module
- Jumper Wires
- Breadboard
- Screw Terminal Expansion Board for ESP8266
- DIYables Sensor Kit (18 sensors/displays)
Wiring
The module has four pins: VCC, GND, DO, and AO. Connect VCC to a 3.3V-5V source and GND to ground. Wire DO, AO, or both to the ESP8266 depending on which output you want to use, since the module lets you choose digital, analog, or both at once. The example code here reads the DO pin on D7.
How It Works
A built-in potentiometer on the module sets the light/dark threshold. When ambient light rises above that threshold, DO goes LOW and the DO-LED turns on; when light drops below it, DO goes HIGH and the DO-LED turns off. The AO pin outputs a value that decreases as light gets brighter and increases as it gets darker, and the potentiometer has no effect on this value. A separate PWR-LED just shows the module is powered.
Code
The DO-pin sketch sets D7 as an input and reads it with digitalRead() in the loop. HIGH means no light is detected, so it prints "The light is NOT present"; LOW prints "The light is present". A companion sketch for the AO pin reads the analog value with analogRead() and prints it to the Serial Monitor, so you can cover and uncover the sensor and watch the number rise and fall as light changes.
esp8266-ldr-module.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://newbiely.com/tutorials/esp8266/esp8266-ldr-module