Sensing the world · Lesson 4 of 5· 15 min
A lamp that switches on at dusk
Why this matters
A security light or a market stall lamp that turns itself on when it gets dark saves power and saves someone remembering.
The light sensor
A photoresistor changes with light. In Wokwi, the photoresistor sensor module gives an analog value on its AO pin.
Open a tool
Wokwi simulator
Free, nothing to install. Works best on a laptop; on a phone you can still read the steps and the code below.
Opens wokwi.com in a new tab. Come back here when you are done.
Step by step
-
Add a photoresistor sensor module in Wokwi.
-
Wire VCC to 3V3, GND to GND and AO to GP26.
-
Keep an LED with its resistor on GP16.
from machine import ADC, Pin
import time
light = ADC(26)
lamp = Pin(16, Pin.OUT)
while True:
print(light.read_u16())
time.sleep(0.5)
Choose the threshold from real readings
Do not guess. Run the program and move the light slider to bright day, then to night. Write down both numbers. Your threshold goes between them.
Then finish the program: if the reading is on the dark side of your threshold, switch the lamp on; otherwise off. Check which way your numbers go first: on some modules dark gives a bigger number, on others a smaller one.
Your task
Add a gap so the lamp does not flicker at dusk: switch on a little past the threshold, and off a little before it. This is called hysteresis.