Raspberry Pi GPIO with Python: gpiozero, lgpio and RPi.GPIO Compared (2026)
Want to blink an LED, read a button or dim a light from a Python script on your Raspberry Pi? There are three libraries for the job: gpiozero, lgpio and RPi.GPIO. This guide shows you which one to pick, how to use each of them on any model, including the Raspberry Pi 5, and what the most common error messages mean.
We tested every Python example on a Raspberry Pi 5 running the latest Raspberry Pi OS (kernel 6.18, gpiozero 2.0.1, lgpio 0.2.2, rpi-lgpio 0.6) in November 2026.
In short
For new projects, use gpiozero: it comes preinstalled and works on every model, including the Raspberry Pi 5.
- Existing RPi.GPIO code usually runs unchanged on the latest Raspberry Pi OS, because the drop-in replacement rpi-lgpio is preinstalled.
- Don’t install the original
python3-rpi.gpiopackage: it replaces rpi-lgpio and doesn’t work on the Pi 5. - Pick lgpio if you want to control every pin yourself, for example to get button presses with exact timestamps.
Which Python GPIO Library Should You Use?
The short answer: if you’re starting fresh, use gpiozero. If you want to control pins and events yourself, use lgpio. Existing RPi.GPIO code keeps working; you just need to check which package it’s running on.
The latest Raspberry Pi OS ships with all three libraries. RPi.GPIO comes in two flavors, though: the original and rpi-lgpio. rpi-lgpio offers the same API as the original but uses lgpio under the hood. Since the October 22, 2024 image, Raspberry Pi OS has shipped it instead of the original, so import RPi.GPIO gets you rpi-lgpio.
| Library | Raspberry Pi 5 | Pi 4 and older | Preinstalled | Best for |
|---|---|---|---|---|
| gpiozero | ✅ | ✅ | yes | new projects, getting started |
| lgpio | ✅ | ✅ | yes | more control over pins and events |
| RPi.GPIO via rpi-lgpio | ✅ | ✅ | yes, since October 2024 | keeping existing code |
Original RPi.GPIO (python3-rpi.gpio) | ❌ | with caveats | no | no longer needed |
The original RPi.GPIO writes straight to the registers of the GPIO hardware. On the Pi 5, though, the pins sit on the new RP1 chip, which the package doesn’t support. That’s why it fails on the Pi 5 with RuntimeError: Cannot determine SOC peripheral base address. It still runs on older models, but edge detection (noticing when a pin changes from 0 to 1 or back, for example when you press or release a button) with add_event_detect fails on current kernels (kernel issue 6037). gpiozero, lgpio and rpi-lgpio go through the Linux kernel’s /dev/gpiochip interface instead, so they work on every model.
Comparison: gpiozero vs lgpio vs RPi.GPIO
Here’s how the three differ in day-to-day use:
| Feature | gpiozero | lgpio | RPi.GPIO (via rpi-lgpio) |
|---|---|---|---|
| Ease of use | very easy | moderate | moderate |
| Claiming pins | automatic | you reserve each pin yourself | GPIO.setup() |
| PWM | software PWM | software PWM | software PWM |
| Events | when_pressed and friends | callbacks on kernel events | add_event_detect |
| Amount of code | very little | moderate | moderate |
| Maintenance | active, releases in 2026 | maintained, few releases | original: no release since 2022; rpi-lgpio ships with Raspberry Pi OS |
What You Need
- A Raspberry Pi with a 40-pin header, such as a Raspberry Pi 5*, running Raspberry Pi OS. Python 3 comes preinstalled (currently 3.13; the previous release, which ships Python 3.11, works just as well)
- LEDs, 330 Ω resistors and push buttons, all included in the Elegoo Electronic Fun Kit*
- A breadboard, for example the Elegoo 830-point breadboard (3-pack)*
- Male-to-female jumper wires* for the Pi’s pins
- Optional: a T-cobbler breakout board* that brings all 40 pins onto the breadboard, clearly labeled
- Optional: extra buttons, such as a 250-piece push button set*
If you’ve never worked with GPIO before, start with our beginner’s guide to GPIO pins, which also covers the pins’ 3.3 V limit. New to Python? Our introduction to Python on the Raspberry Pi covers the basics.
Checking the Installation
On the latest Raspberry Pi OS, including Lite, there’s nothing to install: gpiozero, lgpio and rpi-lgpio come preinstalled. To confirm that gpiozero and lgpio are available, run this command. It should print ok; if one is missing, you’ll see ModuleNotFoundError:
python3 -c "import gpiozero, lgpio; print('ok')"
If they’re missing on an older or stripped-down install, add them from the official repository:
sudo apt update
sudo apt install python3-gpiozero python3-lgpio
If you’re running existing RPi.GPIO code, this command tells you whether it uses rpi-lgpio or the original package. Systems installed from an image older than October 22, 2024 usually still have the original:
python3 -c "import RPi.GPIO, sys; print('rpi-lgpio' if 'lgpio' in sys.modules else 'original RPi.GPIO')"
If it says original RPi.GPIO or you get ModuleNotFoundError: No module named 'RPi', install rpi-lgpio (apt removes the original automatically):
sudo apt install python3-rpi-lgpio
Many older guides tell you to run
sudo apt install python3-rpi.gpio. Skip it: the command removes the preinstalled rpi-lgpio and installs the original instead. After that, none of your RPi.GPIO code will run on the Pi 5. If you’ve already done it, sudo apt install python3-rpi-lgpio puts things back the way they were.
If you work in a virtual environment (venv), create it with --system-site-packages so Python can see the preinstalled packages. Otherwise your script fails with ModuleNotFoundError. Create and activate it like this:
python3 -m venv --system-site-packages ~/gpio-env
source ~/gpio-env/bin/activate
Don’t try to pip-install the packages into an empty venv instead. On 64-bit Raspberry Pi OS, pip install lgpio or pip install rpi-lgpio usually fails during the build with error: command 'swig' failed, because there are no prebuilt 64-bit wheels for Python 3.13.
Wiring It Up
Every example in this guide uses the same circuit. Build it once, then try each library with it:
- LED: from GPIO17 (pin 11) through a 330 Ω resistor to the LED’s longer leg, with the shorter leg going to GND (pin 9).
- Button: between GPIO27 (pin 13) and GND (pin 14). On four-leg buttons, use two diagonally opposite legs. You don’t need a resistor: the examples turn on the Pi’s internal pull-up resistor, which holds the pin high (1) until pressing the button pulls it low (0).
GPIO17 is the GPIO number; pin 11 is its position on the header. In Python, you always use the GPIO number. The GPIO pins run at 3.3 V, so never connect 5 V directly to a GPIO, as that can permanently damage the Pi. Our interactive pinout tool shows where each pin is.
gpiozero — The Beginner-Friendly Approach
gpiozero works with objects such as LED, Button and MotionSensor instead of individual pin commands. LED(17) means GPIO17, not pin 17 on the header. Behind the scenes, gpiozero uses lgpio, so you never have to touch lgpio directly.
Blinking an LED
With the circuit above, the LED on GPIO17 blinks once a second:
from gpiozero import LED
from time import sleep
led = LED(17) # GPIO17 (BCM number), physical pin 11
while True:
led.on()
sleep(1)
led.off()
sleep(1)
Save the code as blink.py, for example with nano (Ctrl+O and Enter to save, Ctrl+X to exit), and run it with Python. You run every example in this guide the same way, and Ctrl+C stops it:
nano blink.py
python3 blink.py
led.blink() does the same in fewer lines. gpiozero handles the blinking in the background, and pause() keeps the script running:
from gpiozero import LED
from signal import pause
led = LED(17)
led.blink(on_time=0.5, off_time=0.5)
pause() # keep the script running until Ctrl+C
Reading a Button
This script prints a message whenever you press or release the button on GPIO27. gpiozero turns on the internal pull-up resistor for you.
from gpiozero import Button
from signal import pause
button = Button(27)
button.when_pressed = lambda: print("Pressed!")
button.when_released = lambda: print("Released!")
pause()
Controlling an LED with a Button
The LED stays on for as long as you hold the button:
from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(27)
button.when_pressed = led.on
button.when_released = led.off
pause()
Dimming an LED with PWM
PWM switches the pin on and off very quickly. The larger the share of on-time, the brighter the LED looks. For brightness control, use PWMLED. Values range from 0 (off) to 1 (full brightness). gpiozero generates the PWM signal in software, so this works on any GPIO pin.
from gpiozero import PWMLED
from signal import pause
from time import sleep
led = PWMLED(17)
# Fade in slowly
for i in range(0, 101, 5):
led.value = i / 100
sleep(0.05)
# Pulse in the background
led.pulse(fade_in_time=1, fade_out_time=1)
pause() # without pause() the script ends and the LED goes off
pulse() runs in the background, but only for as long as the script does. Without pause() at the end, the program finishes right away and the LED goes off.
lgpio — The Modern Low-Level Library
lgpio is the library gpiozero is built on. It talks to the pins through the Linux kernel’s gpiochip interface. You claim each pin yourself and receive edge events straight from the kernel, each with a nanosecond timestamp. gpiozero reports button presses as events too; lgpio is the better choice when you want precise control over which pin is claimed when, or want to read and write several pins at once as a group.
Basic Structure
The examples use the same circuit. With lgpio, you first open a handle to the GPIO chip, a bit like opening a file, then claim your pins and close the handle when you’re done:
import lgpio
import time
h = lgpio.gpiochip_open(0) # gpiochip0 = the 40-pin header
try:
lgpio.gpio_claim_output(h, 17) # GPIO17 as output
for _ in range(5):
lgpio.gpio_write(h, 17, 1)
time.sleep(0.5)
lgpio.gpio_write(h, 17, 0)
time.sleep(0.5)
finally:
lgpio.gpiochip_close(h) # releases every pin claimed through h
Use
gpiochip_open(0); on the latest Raspberry Pi OS that works on every model. On the Pi 5, older guides use gpiochip_open(4) because that was the chip’s number before kernel 6.6.45. That still works, since Raspberry Pi OS adds a /dev/gpiochip4 link. If uname -r on your Pi 5 shows a version below 6.6.45, run sudo apt full-upgrade and reboot to get the new kernel, and 0 applies from then on. To see which chip the header pins belong to, run the preinstalled gpiodetect (on the Pi 5, look for pinctrl-rp1), and gpioinfo shows which pins are in use.
Button Interrupt with lgpio
lgpio reports edges as events from the kernel, so your script doesn’t have to keep checking the pin. To get them, claim the pin with gpio_claim_alert(). With gpio_claim_input(), you can still read the pin, but the callback silently never fires.
import lgpio
from signal import pause
def button_callback(chip, gpio, level, timestamp):
if level == 0: # falling edge = button pressed
print(f"Button on GPIO{gpio} pressed!")
h = lgpio.gpiochip_open(0)
# Claim as an alert, or the kernel won't report any edges
lgpio.gpio_claim_alert(h, 27, lgpio.FALLING_EDGE, lgpio.SET_PULL_UP)
lgpio.gpio_set_debounce_micros(h, 27, 5000) # optional: 5 ms debounce
cb = lgpio.callback(h, 27, lgpio.FALLING_EDGE, button_callback) # edge argument is ignored, the claim decides
print("Waiting for a button press (Ctrl+C to quit)...")
try:
pause()
except KeyboardInterrupt:
pass
finally:
cb.cancel()
lgpio.gpiochip_close(h)
Three things that often trip people up:
- The claim, not the callback, decides which edges you get. lgpio ignores the edge argument of
lgpio.callback(). If you claim the pin withlgpio.BOTH_EDGES, you get both edges no matter what the callback says. Tell them apart withlevel(0 = falling, 1 = rising). - Debouncing: Buttons bounce, meaning the contact closes several times in quick succession when you press it.
lgpio.gpio_set_debounce_micros(h, 27, 5000)right after the claim filters that out (5 ms in this example). Debouncing only applies to pins claimed as alerts. - Cleaning up: The
try/finallyblock cancels the callback and closes the chip even after Ctrl+C. Without it, Ctrl+C would end the script before the callback and chip are released.
Software PWM with lgpio
tx_pwm() generates a software PWM signal on any GPIO pin, as long as you’ve claimed it as an output first. In this example, that’s GPIO17, where the LED is connected. If you leave out gpio_claim_output(), lgpio won’t raise an error, but nothing happens on the pin. In our test, GPIO17 didn’t go high once in 1,500 samples without the claim; with the claim, it was high 738 times, about half the time.
import lgpio
import time
h = lgpio.gpiochip_open(0)
lgpio.gpio_claim_output(h, 17) # without this claim nothing happens on the pin
lgpio.tx_pwm(h, 17, 1000, 50) # 1000 Hz, 50% duty cycle
time.sleep(2)
lgpio.tx_pwm(h, 17, 1000, 20) # 20% duty cycle
time.sleep(2)
lgpio.tx_pwm(h, 17, 0, 0) # stop PWM
lgpio.gpiochip_close(h)
Software PWM has some timing jitter. For servos, the lgpio author recommends it for testing only (lgpio docs). For true hardware PWM, use the pwm or pwm-2chan overlay in config.txt, as described in the kernel’s overlay documentation. You then control the channel through /sys/class/pwm, not with tx_pwm() or gpiozero.
RPi.GPIO — Reusing Existing Code
Lots of tutorials and books still use RPi.GPIO. You don’t need to rewrite that code: on the latest Raspberry Pi OS it runs on rpi-lgpio, on the Pi 5 and older models alike. We tested outputs, inputs with pull-ups, add_event_detect and GPIO.PWM on a Pi 5. The circuit stays the same. If your system predates October 2024, first run the check from Checking the Installation to see which package you have.
Blinking an LED with RPi.GPIO
You may know the basic pattern from older guides: pick a numbering scheme, set up the pin, turn it on and off and clean up at the end.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) # use BCM (GPIO) numbers
GPIO.setup(17, GPIO.OUT) # GPIO17 as output
try:
for _ in range(5):
GPIO.output(17, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(17, GPIO.LOW)
time.sleep(0.5)
finally:
GPIO.cleanup() # reset the pins (always do this)
Reading a Button with RPi.GPIO
The simplest version checks the button in a loop:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP) # enable the pull-up
try:
while True:
if GPIO.input(27) == GPIO.LOW: # LOW = button pressed
print("Button pressed!")
time.sleep(0.3) # simple debounce
time.sleep(0.05)
finally:
GPIO.cleanup()
Button Events with add_event_detect
Instead of checking the button over and over, you can get notified every time it’s pressed. bouncetime sets the debounce time in milliseconds, filtering out the contact closing several times as you press. With rpi-lgpio, this works on the Pi 5 too:
import RPi.GPIO as GPIO
from signal import pause
def pressed(channel):
print(f"Button on GPIO{channel} pressed!")
GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(27, GPIO.FALLING, callback=pressed, bouncetime=200)
try:
pause()
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
Dimming an LED with GPIO.PWM
Just like the original, GPIO.PWM generates a software PWM signal (100 Hz in this example). With rpi-lgpio, you’ll see a TypeError from PWM.__del__ on exit after pwm.stop() and GPIO.cleanup(). It’s harmless, since the script has already finished its work by then.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
pwm = GPIO.PWM(17, 100) # 100 Hz
pwm.start(0)
try:
for duty in range(0, 101, 5): # fade in
pwm.ChangeDutyCycle(duty)
time.sleep(0.05)
finally:
pwm.stop()
GPIO.cleanup()
rpi-lgpio doesn’t behave exactly like the original. If another program or a kernel driver such as SPI is already using a pin, you’ll get lgpio.error: 'GPIO busy', 'GPIO not allocated' or 'unexpected error'. Debouncing with bouncetime also works a little differently. The rpi-lgpio docs have the full list, and our Raspberry Pi 5 GPIO article lists every error message with its fix for the Pi 5.
Running a GPIO Script Automatically at Boot
The usual way to start a script at boot is systemd. Create a service file:
sudo nano /etc/systemd/system/my-gpio-script.service
Add the following, replacing yourname with your username and my_script.py with your script. There’s no default pi user anymore; it was dropped in 2022. If you use a venv, point ExecStart at the venv’s Python, e.g. /home/yourname/gpio-env/bin/python instead of /usr/bin/python3. Save and exit as before with Ctrl+O, Enter and Ctrl+X.
[Unit]
Description=My GPIO Python script
After=network.target
[Service]
ExecStart=/usr/bin/python3 /home/yourname/my_script.py
WorkingDirectory=/home/yourname
StandardOutput=journal
StandardError=journal
Restart=on-failure
User=yourname
[Install]
WantedBy=multi-user.target
That user needs write access to the working directory, because lgpio (and therefore gpiozero) creates a helper file called .lgd-nfy… there when it starts. If the directory isn’t writable, or it already holds a file of that name owned by another user, the script fails with FileNotFoundError. So use the home directory, not /tmp.
The user also needs to be in the gpio group. The account you created when setting up the Pi already is. To add another user:
sudo usermod -aG gpio yourname
Then enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable my-gpio-script.service
sudo systemctl start my-gpio-script.service
# Check the status
sudo systemctl status my-gpio-script.service
Anything your script prints ends up in the systemd journal. To watch it live:
journalctl -u my-gpio-script.service -f
Common Errors and Solutions
| Error message | Cause | Fix |
|---|---|---|
RuntimeError: Cannot determine SOC peripheral base address | Original RPi.GPIO on the Pi 5, installed via apt or via pip in a venv | sudo apt install python3-rpi-lgpio. In a venv, run pip uninstall RPi.GPIO and recreate the venv with --system-site-packages |
RuntimeError: This module can only be run on a Raspberry Pi! | Original RPi.GPIO on a computer that isn’t a Raspberry Pi, or in a container | Run the script on the Pi itself |
lgpio.error: 'GPIO busy' | Another program, a second gpiochip_open() in the same script or a kernel driver such as SPI is using the pin | Stop the other program, check claimed pins with the preinstalled gpioinfo, avoid the SPI and I2C pins. Reboot only as a last resort |
lgpio.error: 'GPIO not allocated' | Usually GPIO.setup(pin, GPIO.OUT) on a pin that another program or a driver such as SPI is using | Same as for 'GPIO busy' |
lgpio.error: 'can not open gpiochip' | Your user isn’t in the gpio group, or gpiochip_open() got a chip number that doesn’t exist | sudo usermod -aG gpio $USER, then log out and back in. Use chip 0 in gpiochip_open() |
BadPinFactory: Unable to load any default pin factory! | gpiozero can’t reach the pins: usually your user isn’t in the gpio group, or the venv can’t see lgpio | Add the user to the gpio group (see 'can not open gpiochip' above); use a venv with --system-site-packages |
ModuleNotFoundError: No module named 'gpiozero' (or 'RPi') | venv without access to the system packages | Recreate the venv with --system-site-packages |
FileNotFoundError: [Errno 2] No such file or directory: '.lgd-nfy-3' | Working directory isn’t writable (common with systemd services), or it already contains another user’s file of that name (e.g. in /tmp) | Start the script from your home directory; for systemd, set WorkingDirectory to match |
| LED doesn’t light up | LED inserted backwards or wired to the wrong pin (e.g. physical pin 17 instead of GPIO17) | Longer leg to the GPIO, shorter leg to GND. LED(17) is pin 11 |
Next Steps
- Add sensors: Read I2C sensors like the BME280 (temperature and air pressure) with smbus2 or an Adafruit library. The DHT22 temperature and humidity sensor* uses its own single-wire protocol and needs a dedicated library, such as Adafruit’s.
- Add a display: Hook up an OLED screen over I2C or SPI, for example with Adafruit’s CircuitPython libraries.
- Control motors: Servos run on PWM, and gpiozero has a
Servoclass for them. For smooth, jitter-free movement, use hardware PWM; the overlay docs are linked in the lgpio section. Stepper motors need a driver board. - Smart home: Home Assistant has removed its old GPIO integration. Instead, your script can report pin states to Home Assistant over MQTT.
To see which pins support I2C, SPI or UART, check our pinout tool for every model with a 40-pin header.
Wrapping Up
These days, gpiozero is the way to go for GPIO in Python: it’s preinstalled, runs on every model and needs the least code. Old RPi.GPIO code keeps working through rpi-lgpio, as long as you don’t install the original package. Pick lgpio when you want full control over pins and events. Have fun building!
Frequently Asked Questions About GPIO with Python
Use gpiozero for new projects and lgpio when you need more control. Existing RPi.GPIO code keeps running on the latest Raspberry Pi OS through the preinstalled rpi-lgpio. Only the original python3-rpi.gpio package fails on the Pi 5, because it accesses registers directly, and those are laid out differently on the Pi 5’s new RP1 chip.
BOARD counts the header pins from 1 to 40, with odd numbers in one row and even numbers in the other. BCM refers to the GPIO number: physical pin 11, for example, is GPIO17. The numbers are the same on the Pi 5. gpiozero expects BCM numbers by default, while lgpio uses the chip’s line numbers, which match the BCM numbers on the Pi.
It usually means your user isn’t in the gpio group. Run sudo usermod -aG gpio $USER, then log out and back in. The account you created during setup is already in the group, so this mostly affects new users and services. gpiozero reports BadPinFactory in this case. You get the same lgpio message if gpiochip_open() uses the wrong chip number.
No. At any given moment, a GPIO pin is either an input or an output, not both. You can switch the direction in your script, though.
The GPIO pins run at 3.3 volts, not 5 volts. Applying 5 V directly to a GPIO pin can permanently damage your Raspberry Pi. For 5 V sensors and modules, use a level shifter.
