Automatic Night Lamp using LDR
Build an automated ambient light controller that activates illumination when surrounding light drops below a threshold.
Municipal street lighting systems, solar garden pathway lamps, and automatic smartphone screen brightness adjustment.
A Light Dependent Resistor (LDR) exhibits high resistance in the dark (>100kΩ) and low resistance in bright light (<1kΩ). In a voltage divider circuit with a fixed 10kΩ resistor, the analog voltage read by the ADC varies linearly with ambient light intensity.
Pin Connection & Wiring Table
| Component Pin / Terminal | Microcontroller Pin (ESP32 / Arduino) | Wiring Note |
|---|---|---|
| LDR Leg 1 | 3.3V / 5V | Power rail |
| LDR Leg 2 / 10k Resistor junction | GPIO 34 (ADC1_CH6) / A0 | Analog input signal |
| 10k Resistor other leg | GND | Ground pull-down |
| LED Anode via 220Ω | GPIO 4 / Pin 9 | Output light control |
| LED Cathode | GND | Ground |
Step-by-Step Plug & Play Assembly
Create a voltage divider: place LDR and 10kΩ resistor in series between 3.3V and GND.
Connect the junction between the LDR and 10kΩ resistor to ESP32 pin 34.
Wire the LED with its 220Ω resistor to GPIO 4.
Cover the LDR with your palm to verify darkness detection.
Complete Tested Source Code
// NovaCircuit Project 2: Automatic Night Lamp
const int LDR_PIN = 34; // ADC pin
const int LED_PIN = 4;
const int LIGHT_THRESHOLD = 1500; // Calibrate according to room lighting (0-4095 on ESP32)
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
Serial.println("Automatic Night Lamp Ready");
}
void loop() {
int sensorValue = analogRead(LDR_PIN);
Serial.print("Ambient Light ADC: ");
Serial.println(sensorValue);
if (sensorValue < LIGHT_THRESHOLD) {
digitalWrite(LED_PIN, HIGH); // Turn lamp ON in darkness
Serial.println("Status: DARK -> Lamp ON");
} else {
digitalWrite(LED_PIN, LOW); // Turn lamp OFF in bright daylight
Serial.println("Status: BRIGHT -> Lamp OFF");
}
delay(500);
}analogRead() samples the 12-bit ADC on ESP32 (values 0-4095). When light decreases, resistance rises and voltage drops below LIGHT_THRESHOLD, triggering the if condition to drive GPIO 4 HIGH.
Expected Physical Output
- •Threshold mismatch: Open Serial Monitor to observe live ADC numbers, then adjust LIGHT_THRESHOLD accordingly.
- •LDR readings inverted: Swap the 3.3V and GND connections of the voltage divider if you prefer rising ADC values in darkness.
- •Operate strictly on 3.3V-5V DC. Do not use high-voltage AC incandescent lamps.
Related Book Chapter & Hardware Kit
Covered in depth within Chapter 6: Sensors and Their Applications. Build this easily with the Sensor Explorer Kit.