Use GPIO from Python

Using the GPIO Zero library makes it easy to control GPIO devices with Python. The library is comprehensively documented at gpiozero.readthedocs.io.

For information about GPIO hardware, see GPIO hardware.

LED control

The following example code controls an LED connected to GPIO17:

from gpiozero import LED
from time import sleep

led = LED(17)

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

Run this in an IDE like Thonny, and the LED will blink on and off repeatedly.

LED methods include on(), off(), toggle(), and blink().

Read button state

The following example code reads the state of a button connected to GPIO2:

from gpiozero import Button
from time import sleep

button = Button(2)

while True:
    if button.is_pressed:
        print("Pressed")
    else:
        print("Released")
    sleep(1)

Button functionality includes the properties is_pressed and is_held; callbacks when_pressed, when_released, and when_held; and methods wait_for_press() and wait_for_release.

Control an LED with a button

The following example code reads the state of a button connected to GPIO2, and lights an LED connected to GPIO17 when the button is pressed:

from gpiozero import LED, Button

led = LED(17)
button = Button(2)

while True:
    if button.is_pressed:
        led.on()
    else:
        led.off()

Alternatively:

from gpiozero import LED, Button

led = LED(17)
button = Button(2)

while True:
    button.wait_for_press()
    led.on()
    button.wait_for_release()
    led.off()

or:

from gpiozero import LED, Button

led = LED(17)
button = Button(2)

button.when_pressed = led.on
button.when_released = led.off