Automatic night light
A light sensor (LDR) turns an LED up as the room gets darker.
Sensors · Beginner
In a real product: Automatic night light (Smart home): Light level decides how bright the lamp should be.
A light-dependent resistor (LDR) has less resistance in bright light and much more in the dark. On this module it forms a voltage divider, so its analog output rises as it gets darker. The sketch dims an LED up as the light fades.
What you'll learn
- Reading a light sensor with
analogRead() - Turning a reading range into a brightness with
map()andconstrain() - Calibrating: choosing the readings that count as "light" and "dark"
How it works
The module's AO pin goes to A0. In bright light (500 lux) it reads about 250; in near darkness it reads over 900.
map(reading, 300, 900, 0, 255) turns 300–900 into a brightness, and constrain() keeps it within 0–255 when the reading goes past either end. The LED on pin 9 gets that brightness with PWM, so it fades in smoothly as the light drops instead of snapping on.
The module also has a digital output (DO), HIGH when it is darker than its trimmer's threshold, if you only need on/off.
Try this
- Drag the light sensor's lux slider (click the part) down to 1 and watch the LED come up.
- Use DO instead, so the LED is simply on or off.
- Log the light level every minute to see a whole day's light curve.
sketch.ino
// An automatic night light: the darker it is (higher reading on A0), the brighter the LED on pin 9.
const int LDR = A0;
const int LED = 9;
unsigned long lastPrint = 0;
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = analogRead(LDR); // higher when darker
int brightness = constrain(map(reading, 300, 900, 0, 255), 0, 255);
analogWrite(LED, brightness);
if (millis() - lastPrint >= 500) {
lastPrint = millis();
Serial.print("Light reading: ");
Serial.print(reading);
Serial.print(" LED: ");
Serial.println(brightness);
}
}