Build a night lightTinkerPieCircuit tutorial 11 of 24 · Intermediate · 15 minutes
A light sensor (LDR) and a resistor form a voltage divider. The LED turns on when the room gets dark.
Open this circuit in TinkerPieCircuit (free, runs in your browser)
What you will learn
- What a voltage divider is
- How a light sensor changes its resistance
- Using a threshold in code
Parts
Steps
Wire the LED
S1→ 220 Ω → LED (+), LED (−) →GND.Make the divider
Wire
3V3→ LDR →P11. Then wireP11→ 10 kΩ resistor →GND. Pin P11 sits in the middle of the two parts.Understand it
In bright light the LDR has a low resistance, so P11 sees a high voltage. In the dark the LDR has a high resistance, so P11 sees a low voltage.
Write the code
If
analogRead(P11)is below 2000 the room is dark, so turn the LED on.Test it
Press ▶ Start. Drag the yellow slider on the LDR down to make it dark. The LED turns on.
The code
function loop() {
const light = analogRead(P11);
Serial.println("light = " + light);
if (light < 2000) {
digitalWrite(S1, HIGH);
} else {
digitalWrite(S1, LOW);
}
delay(100);
}
Copy this into the Code tab. It is Arduino-style JavaScript. The real board uses the same pin names (S1, P10…) in TinkerPie Studio.
How it works
Two resistors in a row share the voltage in proportion to their size. When the LDR resistance changes with light, the voltage at P11 changes too.
← Dim an LED with a knob · All 24 circuit tutorials · Make a servo sweep →