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.

Open Wokwi simulator

Step by step

  1. Add a photoresistor sensor module in Wokwi.

  2. Wire VCC to 3V3, GND to GND and AO to GP26.

  3. 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.

Python

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.

You’re reading for free. Sign in to save your progress, ask questions on any lesson, and earn a certificate when you finish.Sign in to keep my progress →

Lesson 4 of 5