Page cover

GPIO Zero library

The GPIO Zero library offers a simplified approach to interact with the GPIO pins on a Raspberry Pi, providing an intuitive way to control external devices like LEDs, buttons, and sensors.

This library abstracts the complex details of GPIO handling, making it accessible for beginners yet flexible enough for advanced users. Below is a summary of the basic recipes and best practices for using GPIO Zero in your projects:

Importing GPIO Zero

Before using GPIO Zero, you need to import the necessary classes. You can import specific components like Button or LED, or import the entire library.

from gpiozero import Button
# or
import gpiozero

Pin Numbering

GPIO Zero uses Broadcom (BCM) pin numbering. You can also use physical (BOARD) numbering or other schemes by specifying prefixes.

led = LED(17)  # Using BCM numbering
led = LED("BOARD11")  # Using physical numbering

Basic Component Usage

Here's how you can interact with basic components using GPIO Zero:

LED

Turning an LED on and off:

from gpiozero import LED
from time import sleep

red = LED(17)

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

Button

Detecting button presses

Advanced Components and Usage

GPIO Zero also supports more complex interactions, such as controlling traffic lights, reading from sensors, and controlling motors.

Traffic Lights

Controlling a set of traffic lights:

Servo Motors

Controlling a servo motor:

Interactive Projects

GPIO Zero allows for creating interactive projects where components respond to input from sensors or buttons.

Button-Controlled LED

Turn an LED on and off using a button

Robot

Control a robot with basic movements:

Best Practices

  • Keep your script running to maintain control over GPIOs, using signal.pause() or a loop that waits for an event.

  • Clean up GPIO assignments at the end of your script to avoid conflicts on subsequent runs.

  • Use try...except...finally blocks to handle exceptions and perform GPIO cleanup, ensuring that resources are released properly.

By following these guidelines and utilizing the GPIO Zero library, you can create a wide range of projects with your Raspberry Pi, from simple LED blinkers to complex interactive robots.

Last updated

Was this helpful?