Build an automatic night light

Read the photoresistor module with an analog pin and switch on an LED automatically when the room gets dark.
  • Level:Beginner
  • Duration: 30 min
  • Ages 10+
  • Platform: Arduino

What you'll need

Build an automatic night light – EEMENTOR STEM lesson

A photoresistor changes its resistance with the amount of light that falls on it. In this lesson you read it with an analog pin and build a night light that switches on by itself.

What you'll learn

  • The difference between analog and digital inputs
  • How to read a sensor with analogRead()
  • How to choose a threshold from real measurements

What you need

  • UNO R3 board (or any Arduino-compatible board) and USB cable
  • Photo-resistance sensor module from the 45-in-1 kit
  • The board's built-in LED on pin 13
  • 3 jumper wires

Wiring

Check the labels on your module: usually S (signal), the middle pin (+) and - (ground).

Breadboard wiring diagram: Build an automatic night light
Breadboard view. Check each connection against the wiring table below.
Module pin UNO pin
S (signal) A0
Middle (+) 5V
- (ground) GND

Step 1: Measure your room

void setup() {
  Serial.begin(9600);
}

void loop() {
  int light = analogRead(A0); // 0 to 1023
  Serial.println(light);
  delay(200);
}

Open the Serial Monitor at 9600 baud. Write down the value in normal light, then cover the sensor with your hand and write down that value too. Depending on how the module is wired, the number goes either up or down when it gets darker.

Step 2: The night light

Set THRESHOLD halfway between your two values. If your number went up when you covered the sensor, keep DARK_IS_HIGH as true. Otherwise change it to false.

const int SENSOR_PIN = A0;
const int LED_PIN = 13;        // built-in LED
const int THRESHOLD = 500;     // set this from your own measurements
const bool DARK_IS_HIGH = true;

void setup() {
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  int light = analogRead(SENSOR_PIN);
  bool isDark = DARK_IS_HIGH ? (light > THRESHOLD) : (light < THRESHOLD);

  digitalWrite(LED_PIN, isDark ? HIGH : LOW);
  Serial.println(light);
  delay(200);
}

How it works

The module combines the photoresistor with a fixed resistor to form a voltage divider. As the light changes, the voltage on S changes between 0 and 5 V, and analogRead() turns that voltage into a number from 0 to 1023.

Try this next

  • Use the RGB LED module from the kit and change colour with the light level.
  • Add a small gap around the threshold (called hysteresis) so the light doesn't flicker at dusk.

Troubleshooting

  • The value doesn't change: make sure S is on an analog pin (A0), not a digital one.
  • The LED does the opposite of what you expect: flip DARK_IS_HIGH.

Build it yourself

Everything used in this lesson comes in one kit, with parts tested by our engineers.

45-in-1 Sensor Kit | Compatible with Arduino IDE and ESP32 $29.00

Shop the kit