ESP8266 - LDR Module

by DIYables in Circuits > Microcontrollers

7 Views, 0 Favorites, 0 Comments

ESP8266 - LDR Module

esp8266-ldr-module-cover.jpg

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

Wiring

esp8266-ldr-module-wiring-diagram.jpg

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.

/*
* This ESP8266 NodeMCU code was developed by newbiely.com
*
* This ESP8266 NodeMCU code is made available for public use without any restriction
*
* For comprehensive instructions and wiring diagrams, please visit:
* https://newbiely.com/tutorials/esp8266/esp8266-ldr-module
*/

#define DO_PIN D7 // ESP8266's pin connected to DO pin of the ldr module

void setup() {
// Initialize the Serial to communicate with the Serial Monitor.
Serial.begin(9600);
// initialize the ESP8266's pin as an input
pinMode(DO_PIN, INPUT);
}

void loop() {
int light_state = digitalRead(DO_PIN);

if (light_state == HIGH)
Serial.println("The light is NOT present");
else
Serial.println("The light is present");
}

Full Tutorial

The complete tutorial, wiring diagram and code explanation: https://newbiely.com/tutorials/esp8266/esp8266-ldr-module