This night light watches the room with a light sensor. When it gets dark, the LED fades up smoothly, and when the lights come back on, it fades out. Along the way you'll use the Pico's analogue input, PWM to dim an LED, and a trick called hysteresis that stops the light flickering at dusk.
What you need
- A Raspberry Pi Pico of any kind, with headers, and a USB cable that carries data
- A breadboard and some jumper wires
- A light-dependent resistor (LDR), also called a photoresistor. The common 5 mm GL5528 is ideal.
- One 10 kΩ resistor (brown, black, orange)
- One yellow or warm white LED, and one 330 Ω resistor (orange, orange, brown)
- Thonny on your computer
Use an LDR, not a "light sensor module" with a small blue board and a trimmer. Many of those modules give a simple on or off output, which won't work with this code.
Why these parts and values
The sensor. An LDR's resistance falls as light rises. The GL5528's datasheet gives roughly 10 to 20 kΩ at 10 lux (a dim room) and at least 1 MΩ in total darkness. A Pico can't measure resistance directly, so we turn it into a voltage with a voltage divider: the LDR goes from 3.3 V to GP26, and the 10 kΩ resistor goes from GP26 to ground. In bright light the LDR is small and GP26 sits near 3.3 V. In the dark the LDR is huge and GP26 falls towards 0 V.
Why 10 kΩ? A divider is most sensitive when the fixed resistor is close to the sensor's resistance in the range you care about. For a night light that's dim room light, where the GL5528 is in the tens of kilohms, so 10 kΩ works well. The most current the divider can draw is about 0.3 mA, which is nothing.
Readings, not volts. Because the divider is fed from the same 3.3 V that the Pico's ADC uses as its reference, the reading depends only on the two resistances, not on the exact supply voltage. MicroPython's read_u16() gives 0 to 65,535. With 10 kΩ at the bottom, the reading is 65,535 × 10 kΩ ÷ (RLDR + 10 kΩ). The code below turns on below 8,000, when the LDR is about 72 kΩ, and off above 12,000, when it's about 45 kΩ. For a typical GL5528 that's around 1 to 2 lux, which is a room with the lights off and a little light from outside. Every LDR is different, so step 3 shows you how to pick your own numbers.
The LED. A yellow LED drops about 2.1 V, so 330 Ω on a 3.3 V pin gives (3.3 − 2.1) ÷ 330 ≈ 3.6 mA. That's plenty for a night light and gentle on the Pico. White LEDs drop about 3 V, so use 100 Ω for a white one. The LED resistor calculator does the maths for other colours.
The circuit
Step 1: wire it up
Unplug the Pico while you wire. Push it into the breadboard across the centre gap. Our Pico pinout guide shows every pin. The pins you need are on the opposite side to GP0, in the half nearer the USB socket: GP26 is pin 31, AGND is pin 33 and 3V3(OUT) is pin 36. GP15 (pin 20) and GND (pin 18) are on the GP0 side, at the far end from the USB socket.
- Light sensor: put the LDR's two legs in two separate rows. It has no polarity, so either way round is fine. Jumper one row to 3V3(OUT), pin 36. Do not use VBUS or VSYS, which carry about 5 V.
- Jumper the LDR's other row to GP26, pin 31.
- 10 kΩ resistor: from that same GP26 row to AGND, pin 33. AGND is the analogue ground, and using it keeps the readings a little cleaner.
- LED: connect the 330 Ω resistor from GP15, pin 20 to an empty row. Put the LED's long leg in that row and its short leg in another row, then jumper the short leg to GND, pin 18.
- Point the LED away from the LDR. If the LED's light reaches the sensor, the night light can see itself and switch off. The code copes with a little stray light, but not with the LED shining straight at the sensor.
Step 2: set up MicroPython
If your Pico doesn't have MicroPython yet, hold BOOTSEL while plugging it in and let Thonny install it (Tools, Options, Interpreter, MicroPython for the Raspberry Pi Pico). Our Python for electronics guide has more detail.
Step 3: check the sensor and pick your thresholds
Run this in Thonny. It prints a reading twice a second.
from machine import ADC, Pin
import time
sensor = ADC(Pin(26))
while True:
print(sensor.read_u16())
time.sleep_ms(500)
Cover the LDR with your hand and the number should drop a long way. Shine a torch on it and it should rise towards 65,535. Note the reading when the room is as dark as you'd want the light to come on. That's your DARK number. Choose LIGHT about 50% higher, so there's a clear gap between the two. Press the red Stop button in Thonny when you're done.
If the number barely changes, the LDR or resistor isn't in the GP26 row. If it sits near 65,535 whatever you do, the 10 kΩ isn't connected to AGND. If it sits near 0, the LDR isn't connected to 3V3(OUT).
Step 4: the night light code
Paste this into a new file, change DARK and LIGHT if step 3 gave you different numbers, and click Run.
from machine import ADC, Pin, PWM
import time
sensor = ADC(Pin(26)) # GP26 is ADC0
led = PWM(Pin(15)) # GP15 drives the LED
led.freq(1000)
DARK = 8000 # turn on below this reading
LIGHT = 12000 # turn off above this reading
def light_level(samples=8):
total = 0
for _ in range(samples):
total += sensor.read_u16()
time.sleep_ms(2)
return total // samples
def fade(start, end, steps=50):
for i in range(steps + 1):
x = start + (end - start) * i / steps
led.duty_u16(int(65535 * x ** 2.2))
time.sleep_ms(20)
is_on = False
led.duty_u16(0)
while True:
level = light_level()
print(level, "on" if is_on else "off")
if not is_on and level < DARK:
fade(0, 1)
is_on = True
elif is_on and level > LIGHT:
fade(1, 0)
is_on = False
time.sleep_ms(500)
Cover the sensor and the LED fades up over about a second. Uncover it and it fades back down. To run it without a computer, save it to the Pico as main.py and power the Pico from a USB charger.
How it works
- Averaging.
light_level()takes eight readings 2 ms apart and averages them, which smooths out electrical noise. - Hysteresis. If there were one threshold, a reading hovering right on it at dusk would switch the light on and off over and over. With two thresholds, the light only turns on below 8,000 and only turns off above 12,000. Anything in between leaves it as it is. Thermostats work the same way.
- PWM dimming. The Pico can't output "half a volt" on a digital pin. Instead, PWM switches the pin on and off 1,000 times a second, and
duty_u16()sets how much of each cycle it's on, from 0 to 65,535. Your eye averages the flashing into a steady brightness. - The 2.2 in the fade. Your eye's response to brightness isn't linear. A plain straight-line fade seems to jump up quickly and then crawl. Raising the fade position to the power 2.2, a common gamma value, makes the change look even.
- Checking every half second is quick enough for a night light and keeps the Pico mostly idle.
Troubleshooting
- The LED never comes on: run the step 3 code and check the reading really drops below your
DARKvalue when it's dark. If it does, check the LED is the right way round (long leg to the resistor) and its short leg goes to GND. - The LED turns on, then off, then on: its light is reaching the sensor. Turn the LED away, put a small card between them, or widen the gap between
DARKandLIGHT. - It turns on too early or too late: repeat step 3 at the light level you want and change
DARK. Lower numbers mean darker. - It's too bright: change
fade(0, 1)tofade(0, 0.5)andfade(1, 0)tofade(0.5, 0). - Thonny can't find the Pico: try another USB cable, as many only carry power.
Take it further
- Add a button that toggles the light manually, wired like the one in the reaction timer.
- Turn the light off automatically after 30 minutes using
time.ticks_ms(). - Swap the single LED for a strip of addressable LEDs and pick a warm colour. These need 5 V power and a level-shifted data line, so read our guide to powering projects safely first.
- Read our guide to ADCs to learn about the Pico's reference voltage and how to get steadier readings.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.