How to Use gpiozero Library in Python on Raspberry Pi
To use the
gpiozero library in Python on Raspberry Pi, first install it using pip install gpiozero. Then, import the library and create device objects like LED or Button to control GPIO pins with simple commands.Syntax
The basic syntax involves importing the gpiozero library, creating a device object for a GPIO pin, and then using methods to control or read from the device.
- Import:
from gpiozero import LED - Create device:
led = LED(17)assigns GPIO pin 17 to an LED object. - Control device: Use methods like
led.on()orled.off()to turn the LED on or off.
python
from gpiozero import LED led = LED(17) led.on() # Turns the LED on led.off() # Turns the LED off
Example
This example shows how to blink an LED connected to GPIO pin 17 on the Raspberry Pi using gpiozero.
python
from gpiozero import LED from time import sleep led = LED(17) for _ in range(5): led.on() sleep(1) led.off() sleep(1)
Common Pitfalls
Common mistakes include:
- Not running the script with proper permissions (use
sudoif needed). - Incorrect GPIO pin numbering (gpiozero uses BCM numbering by default).
- Forgetting to install the
gpiozerolibrary before running the code. - Not connecting the hardware correctly, which can cause no response or damage.
python
from gpiozero import LED # Wrong pin number or forgetting to install gpiozero causes errors led = LED(999) # Invalid pin led.on()
Quick Reference
| Command | Description |
|---|---|
| from gpiozero import LED, Button | Import device classes |
| led = LED(17) | Create LED object on GPIO 17 |
| led.on() | Turn LED on |
| led.off() | Turn LED off |
| button = Button(2) | Create Button object on GPIO 2 |
| button.is_pressed | Check if button is pressed (True/False) |
Key Takeaways
Install gpiozero with pip before using it on Raspberry Pi.
Use BCM pin numbering when creating device objects like LED or Button.
Control devices easily with simple methods like on(), off(), and is_pressed.
Run scripts with proper permissions to access GPIO pins.
Double-check hardware connections to avoid errors or damage.