AcademyTechnician

Python + GPIO: Blink an LED and Read a Button

Write your first hardware program with the gpiozero library — outputs, inputs and events.

LevelTechnician
Time25 min
Est. cost~$20
Steps5

gpiozero comes pre-installed on Raspberry Pi OS and is the friendliest way to control hardware. Pins are numbered by their GPIO (BCM) number, not their physical position.

Video tutorial

▶ Robotics Back-EndWatch on YouTube ↗

Video by Robotics Back-End, embedded from YouTube. The written steps below are our own and match the parts list.

Mission steps

  1. Create the script

    SSH into the Pi and run nano blink.py, then paste the first example.

  2. Run it

    python3 blink.py — your LED blinks. Press Ctrl+C to stop.

  3. Add a button

    Wire a push button between GPIO27 (pin 13) and GND (pin 14). gpiozero enables the internal pull-up resistor for you.

  4. Use events

    The second example turns the LED on only while the button is held — no loops needed.

  5. Experiment

    Try led.blink(on_time=0.1, off_time=0.9), or use PWMLED to fade brightness.

Code

# blink.py
from gpiozero import LED
from time import sleep

led = LED(17)
while True:
    led.on()
    sleep(0.5)
    led.off()
    sleep(0.5)
# button.py
from gpiozero import LED, Button
from signal import pause

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

button.when_pressed = led.on
button.when_released = led.off
pause()

Tip: test every script on the bench before installing it in a moving machine.

Questions

BCM or BOARD numbering?

gpiozero uses BCM (GPIO numbers) by default. Physical pin 11 is GPIO17. Our GPIO Map shows both.