Fareed Mohmed← Project library

Engineering · Raspberry Pi · Project 11 of 47 · Sensors · Beginner

Automatic night lamp

A light sensor (LDR) switches a lamp on when it gets dark. It is the idea behind street lights and automatic machine lighting.

▶ Open in the simulator

Raspberry Pi simulator drawing of the circuit for Automatic night lamp: the board, its power supply and the parts wired to the 40-pin header

Parts in this circuit

PartType
LDRLight sensor
LampLED

Wiring, pin by pin

Red = 5 V, orange = 3.3 V, black = GND, other colours = signals. “Pin” is the position on the 40-pin header; the GPIO number is what the code uses. Power the Pi from a 5.1 V supply and wire with the power off.

#ColourFrom (part and leg)To (header pin)
1OrangeLDR - 3.3 VPin 1 (3V3)
2ColouredLDR - signalPin 7 (GPIO4)
3BlackLDR - GNDPin 6 (GND)
4ColouredLamp - anode +Pin 11 (GPIO17)
5BlackLamp - cathode -Pin 9 (GND)

Python code (gpiozero)

from gpiozero import LightSensor, LED
from signal import pause

ldr = LightSensor(4, threshold=0.3)     # dark when below 30 %
lamp = LED(17)

def dark():
    lamp.on()
    print("It is dark: lamp ON")

def light():
    lamp.off()
    print("It is light: lamp OFF")

ldr.when_dark = dark
ldr.when_light = light

print("Drag the Daylight slider below 30 %")
pause()

How the code works

You will learn

  • Light-dependent resistor (LDR)
  • Thresholds
  • Events from analog-like sensors

Try this

  • Move the threshold to 0.5 and test again.
  • Add a delay: the lamp should only turn on if it stays dark for 3 seconds.
  • Print a message with the light level every second.

On a real Pi

  • The LDR goes between 3.3 V and the GPIO pin. A 1 microfarad capacitor goes from the pin to GND.
  • Add some hysteresis in real life, or the lamp will flicker at dusk.

Parts to buy

The links open a search on each store, so you see what is in stock today. Check the model, voltage and price before you order.

#ItemQtyBuy / compare
1Raspberry Pi 4 Model B
about 4000 to 9000 INR
1Robu.in Amazon.in ThinkRobotics
2Official 15 W USB-C power supply (5.1 V, 3 A)
Do not use an old phone charger
1Robu.in Amazon.in ThinkRobotics
3microSD card 32 GB, class 10 / A1 (with Raspberry Pi OS)
And a card reader to write it
1Robu.in Amazon.in ThinkRobotics
45 mm LED, yellow1Robu.in Amazon.in ThinkRobotics
5330 ohm resistor, 1/4 W
One per LED
1Robu.in Amazon.in ThinkRobotics
6LDR (GL5528) photoresistor1Robu.in Amazon.in ThinkRobotics
71 µF capacitor1Robu.in Amazon.in ThinkRobotics
8Dupont jumper wires, male-to-female, 20 cm (pack of 40)1Robu.in Amazon.in ThinkRobotics
9Breadboard 830 points
For resistors and shared GND / 5 V
1Robu.in Amazon.in ThinkRobotics
← 10. Temperature alarm with an analog sensorAll projects12. Reaction time game →

This is a learning tool. The simulator checks the program logic, not the electrical design. Never put more than 3.3 V on a GPIO pin.