Skip to main content

Python and GPIO with gpiozero

gpiozero is the recommended Python library for GPIO (extra, not in the lab sheets). It is installed with Raspberry Pi OS and works on every model, including the Raspberry Pi 5.

It is part of the system Python. In the lab venv it is only available if the venv was made with --system-site-packages, otherwise you get No module named 'gpiozero' (fix).

:::warning Raspberry Pi 5 The old RPi.GPIO library does not work on the Raspberry Pi 5. Use gpiozero (or lgpio). Code from older tutorials that uses RPi.GPIO must be rewritten. :::

Running a Python script​

nano led.py # write the code, save with Ctrl+O, Enter, exit with Ctrl+X
python3 led.py # run it

Stop a running script with Ctrl+C. You can also use Thonny (on the desktop) or VS Code Remote - SSH.

Wiring: GPIO17 (pin 11) → 330 ohm resistor → LED long leg (+). LED short leg (−) → GND (pin 9).

from gpiozero import LED
from time import sleep

led = LED(17) # BCM number, not the physical pin

while True:
led.on()
sleep(1)
led.off()
sleep(1)

Shorter: led.blink() then pause() from signal.

Read a button​

Wiring: one side of the button to GPIO22 (pin 15), the other side to GND. gpiozero turns on the internal pull-up resistor for you, so the pin reads "pressed" when it is connected to GND. (Avoid GPIO2/3 for buttons: they have fixed pull-ups for I2C.)

from gpiozero import Button, LED
from signal import pause

button = Button(22)
led = LED(17)

button.when_pressed = led.on
button.when_released = led.off
pause() # keep the program running

Dim an LED (PWM)​

from gpiozero import PWMLED
from time import sleep

led = PWMLED(17)
for level in [0, 0.25, 0.5, 0.75, 1]:
led.value = level # 0 = off, 1 = full brightness
sleep(1)

Buzzer​

from gpiozero import Buzzer
from time import sleep

buzzer = Buzzer(27)
buzzer.beep(on_time=0.2, off_time=0.2, n=3)
sleep(2)

Other useful gpiozero devices​

ClassUse
LED, PWMLED, RGBLEDLights
ButtonPush buttons, switches
MotionSensorPIR motion sensor
DistanceSensorHC-SR04 ultrasonic sensor (see Sensors on the Pi)
Servo, AngularServoServo motors
Motor, RobotDC motors through a motor driver
OutputDeviceRelay modules and anything on/off
CPUTemperatureThe Pi's own CPU temperature

Common errors​

ErrorFix
lgpio.error: 'GPIO busy' or pin already in useAnother script still uses the pin. Stop it (Ctrl+C, or find it with pgrep -a python and kill it).
ModuleNotFoundError: No module named 'RPi'Old tutorial code. Rewrite it with gpiozero.
LED does not lightCheck LED direction (long leg to the GPIO side), the resistor, and that you used the BCM number.
Permission denied on GPIOYour user must be in the gpio group: sudo usermod -aG gpio $USER, then log out and back in.