Python GPIO on Raspberry Pi
gpiozero, RPi.GPIO, PWM fading, and sensor reading with Python
Skills taught: embedded.rpi-gpio
GPIO Pinout and Numbering
The Raspberry Pi 40-pin GPIO header uses BCM numbering (Broadcom chip GPIO numbers) in gpiozero and RPi.GPIO — not physical pin positions. Run pinout in the terminal for a colour diagram. Critical rule: all GPIO pins are 3.3V maximum — never connect 5V signals directly.
# Install gpiozero (usually pre-installed on Pi OS)
sudo apt install python3-gpiozero python3-rpi.gpio -y
# View GPIO pinout diagram in terminal
pinout
# Install Adafruit sensor libraries in a virtual env
python3 -m venv ~/sensors-env
source ~/sensors-env/bin/activate
pip install adafruit-circuitpython-dht adafruit-circuitpython-bmp280
LED and Button with gpiozero
gpiozero provides high-level classes for common components. Its event-driven model (when_pressed, when_released) keeps code clean without polling loops.
from gpiozero import LED, Button
from signal import pause
# BCM pin numbers — check 'pinout' for physical positions
led = LED(17) # GPIO17 = physical pin 11
btn = Button(27, pull_up=True, bounce_time=0.05) # GPIO27 = physical pin 13
# Event-driven: assign callbacks
btn.when_pressed = led.on
btn.when_released = led.off
print("Press the button to toggle the LED. Ctrl+C to exit.")
pause() # block forever, letting gpiozero handle events
PWM: LED Fading and Servo Control
from gpiozero import PWMLED, Servo
from time import sleep
import math
# PWM LED fade (GPIO17)
led = PWMLED(17)
print("Fading LED...")
for _ in range(3):
# Smooth sine-wave fade
for i in range(360):
brightness = (math.sin(math.radians(i)) + 1) / 2 # 0.0 to 1.0
led.value = brightness
sleep(0.005)
# Servo on GPIO18 (use pigpio factory for precise PWM)
# from gpiozero import Servo
# from gpiozero.pins.pigpio import PiGPIOFactory
# factory = PiGPIOFactory()
# servo = Servo(18, pin_factory=factory)
# servo.min() # -90 degrees
# servo.mid() # 0 degrees (neutral)
# servo.max() # +90 degrees
# servo.value = 0.5 # -1.0 to 1.0 range
Reading DHT22 Temperature Sensor
# Install: pip install adafruit-circuitpython-dht
import adafruit_dht
import board
import time
# DHT22 data pin connected to GPIO4 (physical pin 7)
dht = adafruit_dht.DHT22(board.D4)
print("Reading DHT22 temperature sensor...")
while True:
try:
temperature = dht.temperature
humidity = dht.humidity
print(f"Temp: {temperature:.1f}°C Humidity: {humidity:.1f}%")
except RuntimeError as e:
# DHT sensors occasionally fail — not an error, just retry
print(f"Sensor error (retrying): {e}")
finally:
time.sleep(2.0) # DHT22 needs 2s minimum between reads
Low-Level Control with RPi.GPIO
RPi.GPIO gives direct control over pins — equivalent to Arduino's pinMode / digitalRead / digitalWrite. It's useful when you need fine-grained control or are porting Arduino code to Pi.
import RPi.GPIO as GPIO
import time
# Use BCM numbering
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
LED_PIN = 17
BTN_PIN = 27
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BTN_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
while True:
if GPIO.input(BTN_PIN) == GPIO.LOW: # pull-up: LOW = pressed
GPIO.output(LED_PIN, GPIO.HIGH)
print("Button pressed, LED on")
else:
GPIO.output(LED_PIN, GPIO.LOW)
time.sleep(0.05) # 50ms debounce
except KeyboardInterrupt:
print("\nExiting...")
finally:
GPIO.cleanup() # ALWAYS reset GPIO on exit
Warning: Raspberry Pi GPIO pins are 3.3V maximum. Connecting 5V from an Arduino sensor, motor driver, or relay module directly to any GPIO pin will permanently damage the BCM2711 GPIO controller. Use a voltage divider (10 kΩ + 20 kΩ) or a bidirectional level-shifter module for 5V sensors.
Tip: Always call GPIO.cleanup() when your script exits (use a try/finally block). This resets pin modes to inputs, preventing accidental outputs driving voltage into connected hardware if the script crashes and is restarted.
Frequently Asked Questions
Can I use Arduino sensor libraries on Raspberry Pi?
No. Arduino libraries are AVR C++. For Pi, use Python equivalents: Adafruit CircuitPython libraries (pip install adafruit-circuitpython-*) provide identical sensor APIs for most common breakout boards, running on both Pi and microcontrollers.
gpiozero vs RPi.GPIO — which should I use?
Start with gpiozero — it's higher-level, Pythonic, and comes pre-installed. It handles debouncing, event callbacks, PWM, and cleanup automatically. Use RPi.GPIO directly only when you need features gpiozero doesn't expose, or for porting existing RPi.GPIO code.
Why does my PWM servo jitter on Raspberry Pi?
RPi.GPIO software PWM uses a Python thread with ~10% jitter under CPU load. Use pigpio instead: install pigpiod daemon (`sudo systemctl enable pigpiod`) and use gpiozero with PiGPIOFactory. pigpio generates hardware-timed DMA PWM with <1 µs jitter.