Arduino: Zero to First Project · EPISODE 5 · 2:40

Build an Automatic Night Light

Build an Arduino night light that switches on by itself when the room gets dark! A light sensor (LDR) on A0, an LED on pin 9, an if / else — and a pro trick that stops the flicker at sunset. The final project of the series, explained from zero in under 3 minutes.

// CHAPTERS · TAP TO JUMP
// IN THIS EPISODE

What you'll learn

  • The light sensor: a light-dependent resistor (LDR) + a 10 kΩ resistor from 5 V to ground; the middle point goes to A0. More light → more volts → a bigger number.
  • The LED on pin 9: long leg (+) toward pin 9, short leg (−) to ground, with a 220 Ω resistor in the line ((5 − 2) V ÷ 220 Ω ≈ 14 mA — safe).
  • Find your numbers first: open the Serial Monitor (Episode 4). Daylight ≈ 600, covered ≈ 50 → pick a number in between: 300.
  • The code:
    void setup() { pinMode(9, OUTPUT); }
    void loop() {
    int light = analogRead(A0);
    if (light < 300) { digitalWrite(9, HIGH); } else { digitalWrite(9, LOW); }
    }
  • No delay() at all: loop() runs thousands of times a second, so the light reacts instantly. With delay(5000) it could answer up to 5 seconds late.
  • The flicker fix (hysteresis): at sunset the reading wobbles around 300 (298, 302, 299…) and the LED flickers. Use two numbers — ON below 300, OFF above 400; in between it keeps doing what it was doing: Your home thermostat uses the very same trick.
    if (light < 300) digitalWrite(9, HIGH);
    if (light > 400) digitalWrite(9, LOW);
// 30-SECOND SHORTS ON THIS

Quick refreshers