Reading a Light Sensor (LDR) with Arduino
Read the LDR voltage divider from Lesson cb-12 into analogRead, and act on it — a light-aware sketch instead of just a meter reading.
You'll need: the LDR voltage-divider build from Lesson cb-12, its output wired to A0 instead of just a multimeter, plus an LED and resistor on pin 9.
This lesson connects two things you've already built separately: the LDR divider from the Circuit Building section, and analogRead from Lesson ard-07. Wire the divider's junction to A0, exactly as you measured it with a meter in Lesson cb-12 — only now the Uno reads that voltage instead of you reading it off a meter screen.
void setup() {
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop() {
int light = analogRead(A0);
Serial.println(light);
if (light < 300) {
digitalWrite(9, HIGH); // dark -- turn the LED on
} else {
digitalWrite(9, LOW); // bright enough -- stay off
}
}
Watch the Serial Monitor while covering and uncovering the LDR with your hand, and note the range of values you actually see — then adjust the 300 threshold in the code to match your specific LDR and lighting conditions, since that raw number will vary depending on your exact resistor value and room brightness.
This exact pattern — read a sensor, compare it to a threshold, act on the result — is the foundation of an automatic night light, and is worth recognizing as the same shape you'll reuse for almost any sensor-driven decision.