🛠 GPIO en Python : LED et bouton avec gpiozero

Raspberry Pi Zero (2015) — Board Sheet · intermediaire · Schéma : IMG-zero-intermediaire-1-led-bouton-gpiozero.svg — connecteur 40 broches de la Zero (à souder), LED + résistance 330 Ω sur la broche physique 11 (GPIO17), bouton poussoir sur la broche 13 (GPIO27) vers GND, broches 3,3 V et GND repérées.

Goal

Drive the Zero's 40-pin GPIO from Python: an LED and a button with gpiozero. The Zero's header is electrically identical to the Model A+/B+/2B — 3.3 V logic, Broadcom numbering — but it ships unsoldered, so grab a soldering iron first.

Wiring

Code

#!/usr/bin/env python3
# sudo apt install python3-gpiozero
from gpiozero import LED, Button
import signal

led = LED(17)          # BCM numbering: GPIO17 = physical pin 11
btn = Button(27)       # GPIO27 = physical pin 13, button wired to GND

btn.when_pressed = led.on      # event-driven, no polling loop
btn.when_released = led.off

def bye(s, f):
    led.off
    raise SystemExit

signal.signal(signal.SIGINT, bye)
signal.pause         # block forever; the Zero idles at ~0.1 A while waiting

Run with python3 bouton.py, stop with Ctrl-C.

Check

The LED lights while the button is held and goes off on release; after Ctrl-C the LED is cleanly off.

Pitfalls

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials