Automatic Nightlight (Photoresistor + Arduino)
Turn an LED on automatically when it gets dark, using a photoresistor (LDR) voltage divider and analogRead.
Beginner20 min
What you need
Wiring
Hover a pin or a wire to trace the connection.
Code
nightlight.ino
// Turn an LED on when it gets dark (photoresistor voltage divider on A0).
const int ldrPin = A0;
const int ledPin = 13;
const int threshold = 400; // tune for your room (watch the Serial Monitor)
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int light = analogRead(ldrPin); // higher in light, lower in the dark
Serial.println(light);
digitalWrite(ledPin, light < threshold ? HIGH : LOW);
delay(200);
}
Steps
- Build the divider: LDR from 5V to A0, and a 10kΩ resistor from A0 to GND.
- Wire the LED on D13 through a 220Ω resistor, cathode to GND.
- Open the Serial Monitor, note the values in light vs. dark, set `threshold` between them.
- Cover the LDR — the LED should switch on.