LDR (Light Dependent Resistor) is a popular light sensor, and its applications are the most diverse, as for example in streetlights, lighting lamps at night, when dark, and switching off during day, when light. Now let's see how to connect this sensor to NodeMCU.
![]() |
Figure 1 - LDR and NodeMCU |
The sensor
The LDR is a resistor that varies in proportion to the lighting it receives, meaning that depending on the luminosity the value of the internal resistance in Ohm (R|Ω) will vary, from virtually 0R, when under strong light, to about 200kR when in full darkness.
The circuit
Understanding that the LDR is a resistor, and can virtually reach 0R, all we need is an NodeMCU analog port ( Note your NodeMCU card, the ESP8266 version has only one analog input, while the ESP32 version has 15, adapt the circuit or the input port in the code if necessary) and a 100kR resistor to create a Voltage Divider and thus we can read the voltage, in this case it varies from 0V (0 in reading), when in total darkness up to 5V (1023 in reading, considering a 10-bit card with analog input resolution), when in great light. Necessary material:
- 1x - Arduino
- 1x - Protoboard
- 1x - LDR
- 1x - 100kR resistor
![]() |
Figure 2 - Circuit with LDR and NodeMCU |
The code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* AJ Alves (aj.alves@zerokol.com) | |
*/ | |
int ANALOG_PIN = A0; // The NodeMCU Analogic Pin | |
int BOARD_RESOLUTION = 1024 ; // The analogic board resolution, for example NodeMCU ESP8266 is 10 bit (from 0 to 1023) | |
int val = 0; // A varaible to hold the value | |
void setup() { | |
Serial.begin(9600); // Serial Port setup | |
} | |
void loop() { | |
val = analogRead(ANALOG_PIN); // Reading from analogic pin | |
if (val < BOARD_RESOLUTION / 2) { | |
Serial.println("It is DARK!"); | |
} else { | |
Serial.println("It is LIGHT!"); | |
} | |
delay(1000); // Wait 1 second | |
} |
Basicamente o código imprime se "está escuro", caso a tensão recebida esteja abaixo da metade do limiar e "está iluminado" se igual ou acima do limiar.
LDR (Light Sensor) with NodeMCU
Reviewed by AJ Alves
on
quinta-feira, janeiro 04, 2018
Rating:
