ZombieMutex

30 results · ↑ ↓ navigate · Enter open · Esc close

All maker projects

Raspberry Pi / Python / Electronics

Raspberry Pi GPIO: button-controlled LED with Python

Educational reference / No physical hardware testing claimed

A Raspberry Pi can receive a button input on GPIO2 and drive a separate LED on GPIO17. GPIO Zero provides callbacks so the application can wait for input instead of busy-looping.

This is an educational example based on the official documented API. The Python syntax can be validated on a Mac, but actual GPIO wiring and hardware behavior require a Raspberry Pi.

By Jeffrey Monica

How the example works

  1. 01Check GPIO pins

    Use BCM GPIO numbering, not physical header pin numbers. Raspberry Pi GPIO is 3.3 V logic; never apply 5 V directly to GPIO inputs.

  2. 02Connect the components

    Connect a normally open button between GPIO2 and GND. Connect an LED to GPIO17 through an appropriate current-limiting resistor, then GND. Observe LED polarity.

  3. 03Run GPIO Zero

    On the Pi, use a supported Raspberry Pi OS environment with GPIO Zero. Assign when_pressed and when_released callbacks, and keep the process alive with signal.pause().

  4. 04Verify the real circuit

    Press and release the button and check the LED. Shut down/disconnect power before modifying wiring. A passing Python syntax check is not an electrical test.

Reference code

Python. Read the limitations below before using this code with real hardware or network services.

Python
from gpiozero import Button, LED
from signal import pause

# BCM numbering; GPIO is 3.3 V logic.
# Use a current-limiting resistor with the LED.
led = LED(17)
button = Button(2, pull_up=True)
button.when_pressed = led.on
button.when_released = led.off

try:
    pause()
finally:
    button.close()
    led.close()

Test cases to check

  • Pressing the correctly wired button turns the LED on; releasing it turns the LED off.
  • The script stays alive awaiting input; it does not spin in a polling loop.
  • Wrong polarity, wiring, or pin numbering causes incorrect output and must be checked on actual hardware.

Limits & safety

  • No physical Raspberry Pi or circuit was tested for this article.
  • GPIO inputs are not 5 V tolerant; check current, resistor, and board-specific pinout.
  • The script does not expose a network API or claim to harden a remote-controlled Pi.

Official references

Public conversation / GitHub Discussions

Discuss this article

Public comments are being set up. There is no live comment feed yet, and this page will not load a third-party widget until the discussion repository is configured.

Send a private correction or question →