Traffic lights with gpiozero on a Raspberry Pi 4
gpiozero TrafficLights and a Button on a Raspberry Pi 4: press the button and the lights go amber, red for crossing, red and amber, then green again. The whole build, a Raspberry Pi 4 and 2 more parts, runs here in your browser on the Python below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $56. On Mokxi they're free.
The code
The Python exactly as the editor opens it. Change a line there and press Run: the board runs main.py in a Python engine in the page, with gpiozero and RPi.GPIO, and nothing to compile.
# A pedestrian crossing with gpiozero on a Raspberry Pi 4.
# The traffic light module has its own resistors: R on GPIO17 (pin 11),
# Y on GPIO27 (pin 13), G on GPIO22 (pin 15), GND on pin 20. The button is
# between GPIO21 (pin 40) and ground (pin 39); Button() turns on the pull-up.
from gpiozero import TrafficLights, Button
from time import sleep
lights = TrafficLights(red=17, amber=27, green=22)
button = Button(21)
lights.green.on()
print("Green: cars go")
while True:
button.wait_for_press()
print("Button pressed")
sleep(1)
lights.green.off()
lights.amber.on()
print("Amber")
sleep(2)
lights.amber.off()
lights.red.on()
print("Red: cross now")
sleep(5)
lights.amber.on()
print("Red and amber")
sleep(1)
lights.red.off()
lights.amber.off()
lights.green.on()
print("Green: cars go")
Parts list
3 parts, plus the jumper wires. They retail for about $56; on Mokxi they're free.
How it is wired
6 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Raspberry Pi 4 Model B pin GPIO17; Traffic light module pin R
- Raspberry Pi 4 Model B pin GPIO27; Traffic light module pin Y
- Raspberry Pi 4 Model B pin GPIO22; Traffic light module pin G
- Ground: Raspberry Pi 4 Model B pin GND; Traffic light module pin GND
- Ground: Raspberry Pi 4 Model B pin GND; Pushbutton pin 2b
- Raspberry Pi 4 Model B pin GPIO21; Pushbutton pin 1b
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.