Table of Contents
Traffic lights sequence
As well as controlling the whole set of lights together, you can also control each LED individually. With traffic light LEDs, a button and a buzzer, you can create your own traffic lights sequence, complete with pedestrian crossing!
At the top of your file, below
from gpiozero import..., add a line to import the
from time import sleep
Modify your loop to perform an automated sequence of LEDs being lit:
while True: lights.green.on() sleep(1) lights.amber.on() sleep(1) lights.red.on() sleep(1) lights.off()
wait_for_pressso that pressing the button initiates the sequence:
while True: button.wait_for_press() lights.green.on() sleep(1) lights.amber.on() sleep(1) lights.red.on() sleep(1) lights.off()
Try some more sequences of your own.
Now try creating the full traffic lights sequence:
- Green on
- Amber on
- Red on
- Red and amber on
- Green on
Be sure to turn the correct lights on and off at the right time, and make sure you use
sleepto time the sequence perfectly.
Try adding the button for a pedestrian crossing. The button should move the lights to red (not immediately), and give the pedestrians time to cross before moving back to green until the button is pressed again.
Now try adding a buzzer to beep quickly to indicate that it is safe to cross, for the benefit of visually impaired pedestrians.
Design Exercise: ‘Real-world’ Traffic Lights
As a group: talk about what real traffic lights do.
- What inputs do they accept (e.g. buttons, in some cases cars at the light, time of day, etc)
- What happens with the lights?
- Without inputs
- When one our more inputs are received
Design the logic for a typical traffic light with four buttons for pedestrians, an signal for visually impaired pedestrians, and that's.
Write the code and try it out.