Table of Contents
For this worksheet you'll need a breadboard, three LEDs, a button, and the necessary jumper cables and resistors.
To get started, you'll need to place all the components on the breadboard and connect them to the appropriate GPIO pins on the Raspberry Pi.
First, you need to understand how each component is connected:
- A push button requires 1 ground pin and 1 GPIO pin
- An LED requires 1 ground pin and 1 GPIO pin, with a current limiting resistor
Each component requires its own individual GPIO pin, but components can share a ground pin. We will use the breadboard to enable this.
Place the components on the breadboard and connect them to the Raspberry Pi GPIO pins, according to the following diagram:
Note that the row along the long side of the breadboard is connected to a ground pin on the Raspberry Pi, so all the components in that row (which is used as a ground rail) are hence connected to ground.
- Observe the following table, showing which GPIO pin each component is connected to:
Dive into Python
Create a new file by clicking New.
Save the new file straight away by clicking Save; name the file
You have three LEDs: red, amber, and green. Perfect for traffic lights! There's even a built-in interface for traffic lights in GPIO Zero.
from gpiozero import...line to replace
from gpiozero import Button, TrafficLights
led = LED(25)line with the following:
lights = TrafficLights(25, 8, 7)
TrafficLightsinterface takes three GPIO pin numbers, one for each pin: red, amber, and green (in that order).
Now amend your
whileloop to control the
while True: button.wait_for_press() lights.on() button.wait_for_release() lights.off()
TrafficLightsinterface is very similar to that of an individual LED: you can use
blink, all of which control all three lights at once.
while True: lights.blink() button.wait_for_press() lights.off() button.wait_for_release()
## Extra: Add a buzzer
A buzzer requires 1 ground pin and 1 GPIO pin
The table above will change to:
Now you'll add your buzzer to make some noise.
from gpiozero import...line:
from gpiozero import Button, TrafficLights, TonalBuzzer from gpiozero.tones import Tone
Add a line below your creation of
lightsto add a
buzzer = TonalBuzzer(15)
Try adding a
buzzer.stop()into your loop:
while True: lights.on() buzzer.stop() button.wait_for_press() lights.off() buzzer.play(Tone(200.0)) button.wait_for_release()