App - run it as it is

Button and LED

Easy Verified

Its dashboard
Source:
apps/gpio_panel.py
Widgets:
Status, Toggle
You'll need:
A Pi, a push button, an LED, a 330 ohm resistor and jumper wires
What we've checked:
Tested with pretend pins, and run on a real Pi 3A+ against production (2026-09-29) with a real push button and a real LED: the dashboard showed Pressed and Released as the button was pressed and let go, the Toggle lit and darkened the LED, and the LED went out when the program was stopped, with Ctrl+C and with the SIGTERM a systemd service stop sends. Not tried on a Zero W.
Wiring diagram
Wiring diagram. The pin numbers are the Pi's physical header pins.

Everything a Pi does with the real world comes down to two things: reading a pin, and driving a pin. This app does both, and puts them on the dashboard. It is meant to be copied.

You'll need

  • A Raspberry Pi with the 40-pin header, switched off while you wire it
  • A push button
  • An LED and a 330 ohm resistor (the resistor is not optional)
  • A few jumper wires, or a small breadboard

No Pi yet?

You can try it on your computer first. Once you have the code (see Build it), run python gpio_panel.py --simulate. The pins are pretend, and a Test press button appears on the dashboard to press the pretend button. The Toggle drives a pretend LED.

Build it

This project assumes you've registered the device (see Getting Started).

  1. With the Pi switched off, wire the button and the LED as in the diagram.
  2. Switch the Pi on and install the SDK with the pin support: pip install "thepihub[gpio]".
  3. Press View full code above and copy it into a file called gpio_panel.py, or press to copy a command that creates it.

Running it

Run it:

python gpio_panel.py

Then open your dashboard. Press the button: it should say Pressed. Flip the LED switch: the LED lights.

Try changing this

  • Move the LED to another pin. Wire it to a different GPIO pin, then run python gpio_panel.py --led-pin 22 (the button has --button-pin).
  • Swap the button for a door switch. A magnetic door switch (a reed switch) works like a button: the dashboard says Pressed while the magnet is near.
  • Guess first, then check. Switch the LED on, then stop the program with Ctrl+C. What does the LED do? Read The LED starts off, on purpose below to see why.

The educational bit

  • The LED needs a resistor. What do you think would happen without one? (Read the wiring notes below to check your guess.)
  • The LED is off every time the program starts. Why might that be a good rule for something like a heater or a pump?
  • What else could you put on those two pins? A doorbell? An alarm for your bedroom door?

Safety notes

  • Switch the Pi off before you wire anything, and check each wire against the diagram before you switch it back on.
  • Pins give 3.3 V. Never connect one to more than 3.3 V, and never to anything from the mains.
  • An LED always needs its resistor. Anything bigger than an LED (a buzzer, a relay, a motor) needs more than a pin can give: see the wiring notes below.

What next

  • Read the file: it is short.
  • Add a buzzer for a doorbell. It needs a transistor, just as the Motion Trap's infrared light does.
  • When you outgrow it, Motion Trap drives a camera with the same ideas.

Under the hood

The rest of this page is for when you want to know how it works.

Two pins, two jobs

A push button on one pin shows on the dashboard as Pressed or Released, live. A Toggle on the dashboard switches an LED on another pin.

Swap what the pins mean and you have a door switch, a float switch, a relay, a buzzer. The shape does not change.

Nothing new to learn

The pins are plain gpiozero (Button, LED). The app only connects a gpiozero event to a dashboard component, and a dashboard component to a gpiozero call. ThePiHub adds nothing to the GPIO story, except one helper, prepare_pins(), that lets a Python virtual environment find Raspberry Pi OS's pin driver.

The wiring

  • Button: one leg to GPIO 17 (pin 11), the other leg to GND (pin 9). No resistor: the Pi's own pull-up is on.
  • LED: GPIO 27 (pin 13) to a 330 Ω resistor to the LED's anode (long leg); the cathode (short leg) to GND (pin 14).

An LED needs its resistor: a pin gives about 3.3 V and cannot limit the current itself. Anything that draws more than a few milliamps (a relay board, a buzzer, a motor) needs a transistor or a relay board made for 3.3 V logic. Never connect a pin to more than 3.3 V.

The LED starts off, on purpose

Every time the app starts, the LED is off, and it goes off again when the app stops, whatever the Toggle was left on. The Toggle's state is not saved either. An output that quietly comes back on after a power cut is not what most things you would switch want, so the app makes the safe choice for you. It is a deliberate choice, made in two places in the file (the Toggle's persist=False and the led.off() in start()) that you can change.

← Back to Projects

Button and LED

"""GPIO Panel - a button in and an LED out, on the dashboard: the smallest complete example of digital inputs and outputs.

**What it does.** A push button on one pin shows on the dashboard as "Pressed" or "Released", live. A Toggle on the
dashboard switches an LED on another pin. That is all of digital I/O: read a pin, drive a pin. To make your own,
copy this file and change what the two pins mean (a door switch, a relay, a buzzer, a float switch).

**Nothing pihub-specific touches the pins.** They are plain gpiozero (`Button`, `LED`): the app only connects a
gpiozero event to a dashboard component and a dashboard component to a gpiozero call. gpiozero is the whole GPIO
story; pihub adds nothing to it except `prepare_pins()`, which lets a virtual environment find Raspberry Pi OS's pin
driver.

**Hardware.** A Raspberry Pi (any model with the 40-pin header), a push button and an LED:

    Button  one leg -> GPIO 17 (pin 11)     the other leg -> GND (pin 9)        (no resistor: the Pi's own pull-up is on)
    LED     GPIO 27 (pin 13) -> 330 ohm -> LED anode (long leg); LED cathode (short leg) -> GND (pin 14)

An LED needs its resistor: a pin gives about 3.3 V and cannot limit the current itself. For something that draws more
than a few mA (a relay board, a buzzer, a motor), a pin cannot drive it directly: use a transistor or a relay board
made for 3.3 V logic, as the motion trap does for its infrared light. Never connect a pin to more than 3.3 V.

**The LED starts off** every time the app starts, and goes off again when it stops, whatever the Toggle was left on:
an output that quietly comes back on after a power cut is not what most things you would switch want. (The Toggle is
not saved, for the same reason.)

**Run it.** Just run it:

    .venv/bin/python apps/gpio_panel.py

The first time, it prints a link and a short code: open the link while you are logged in, approve it, and answer `y`
when the terminal asks you to confirm the account. That makes the Pi yours, and the platform gives it its id. Every run
after that connects straight away. (`pihub setup` does the same linking on its own, if you would rather do that first.)

**No hardware?** `--simulate` uses gpiozero's pretend pins, so it runs on any computer; press "Test press" on the
dashboard to press the pretend button; the Toggle drives a pretend LED. `pip install "thepihub[gpio]"`
if gpiozero is missing (Raspberry Pi OS already has it; a venv made without `--system-site-packages` does not). The pin
driver, `lgpio`, comes from Raspberry Pi OS (`python3-lgpio`) and is found from a venv as well.
"""

from __future__ import annotations

import argparse
import signal
import time
from typing import Any, List, Optional

from pihub import Device, Program


PROGRAM_ID = "gpio-panel"
PRESSED, RELEASED = "Pressed", "Released"
TEST_PRESS_SECONDS = 0.3


class GpioPanel:
    """The dashboard section: a Status for the button, a Toggle for the LED. `button` is a gpiozero `Button`, `led` a gpiozero `LED`
    (or anything with `when_pressed`, `when_released`, `is_pressed` and `on()`, `off()`). Build it before `device.start()`, then call `start()`."""

    def __init__(self, device: Device, button: Any, led: Any, *, simulated_press: Optional[Any] = None) -> None:
        self.device = device
        self.button = button
        self.led = led
        self.program = Program(id=PROGRAM_ID, name="GPIO Panel")

        self.state = self.program.output(id="button", type="Status")
        button.when_pressed = lambda: self.state.set(PRESSED)
        button.when_released = lambda: self.state.set(RELEASED)

        # persist=False: the LED is off at every start, so the Toggle must not remember "on" (see the docstring at the top).
        self.light = self.program.setting("led", "Toggle", default=False, title="LED", persist=False, apply=self._light_changed)

        if simulated_press is not None:
            press = self.program.command(id="test-press", type="Button")
            press.handler(lambda command: self.test_press(simulated_press))
        device.add_program(self.program)

    def start(self) -> None:
        """After `device.start()`: show where the button is now, and make sure the LED is off."""
        self.led.off()
        self.state.set(PRESSED if self.button.is_pressed else RELEASED)

    def close(self) -> None:
        self.led.off()

    def _light_changed(self, value: Any) -> None:
        self.led.on() if value else self.led.off()

    @staticmethod
    def test_press(pin: Any) -> None:
        """Press and release the pretend button, by driving its mock pin the way a real one would go: low while pressed (pull-up wiring)."""
        pin.drive_low()
        time.sleep(TEST_PRESS_SECONDS)
        pin.drive_high()


def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--server", help="the platform to register with the first time (default: $PIHUB_SERVER, else https://thepihub.com); ignored once registered")
    parser.add_argument("--simulate", action="store_true", help="no hardware: pretend GPIO pins, and a Test press button on the dashboard")
    parser.add_argument("--button-pin", type=int, default=17, help="the GPIO the button is wired to, the other leg to GND (default: 17)")
    parser.add_argument("--led-pin", type=int, default=27, help="the GPIO the LED (through its resistor) is wired to (default: 27)")
    return parser.parse_args(argv)


def build(args: argparse.Namespace, transport: Any = None) -> GpioPanel:
    """The device, its button and LED, and the panel, NOT yet started. `transport` is for tests."""
    try:
        from gpiozero import LED, Button, GPIOZeroError
        from gpiozero import Device as Pins
    except ImportError:
        raise SystemExit('error: this app needs gpiozero: pip install "thepihub[gpio]" (Raspberry Pi OS has it for its own Python)')
    from pihub.gpio import PIN_DRIVER_HELP, prepare_pins

    if args.button_pin == args.led_pin:
        raise SystemExit("error: the button and the LED cannot use the same pin")
    if args.simulate:
        from gpiozero.pins.mock import MockFactory

        Pins.pin_factory = MockFactory()
    else:
        prepare_pins()  # a venv without system packages: the pin driver is Raspberry Pi OS's own

    try:
        # At a terminal, the first run links this machine by code and the platform assigns its id; every run after connects at once.
        device = Device(transport=transport, server=args.server)
    except ValueError as error:
        raise SystemExit(f"error: {error}")

    try:
        button = Button(args.button_pin, bounce_time=0.05)  # pulled up by the Pi; pressed = connected to GND; bounce_time ignores contact chatter
        led = LED(args.led_pin)
    except (GPIOZeroError, OSError) as error:
        raise SystemExit(f"error: {PIN_DRIVER_HELP} ({error})")
    return GpioPanel(device, button, led, simulated_press=button.pin if args.simulate else None)


def main(argv: Optional[List[str]] = None) -> None:
    args = parse_args(argv)
    panel = build(args)
    panel.device.start()
    panel.start()
    print(f"{panel.device.id} is online{' (simulated: press Test press on the dashboard)' if args.simulate else ''}. Ctrl+C to stop.")
    signal.signal(signal.SIGTERM, signal.default_int_handler)  # a service stop (systemd) ends the loop like Ctrl+C, so the LED is switched off
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        pass
    finally:
        print("Stopping...")
        panel.close()
        panel.device.stop()
        panel.button.close()
        panel.led.close()


if __name__ == "__main__":
    main()  # pragma: no cover

Create gpio_panel.py from a terminal

Paste this into a terminal on your Pi (over SSH is fine). It writes the whole program to gpio_panel.py in the folder you are in.

cat > gpio_panel.py << 'EOF'
"""GPIO Panel - a button in and an LED out, on the dashboard: the smallest complete example of digital inputs and outputs.

**What it does.** A push button on one pin shows on the dashboard as "Pressed" or "Released", live. A Toggle on the
dashboard switches an LED on another pin. That is all of digital I/O: read a pin, drive a pin. To make your own,
copy this file and change what the two pins mean (a door switch, a relay, a buzzer, a float switch).

**Nothing pihub-specific touches the pins.** They are plain gpiozero (`Button`, `LED`): the app only connects a
gpiozero event to a dashboard component and a dashboard component to a gpiozero call. gpiozero is the whole GPIO
story; pihub adds nothing to it except `prepare_pins()`, which lets a virtual environment find Raspberry Pi OS's pin
driver.

**Hardware.** A Raspberry Pi (any model with the 40-pin header), a push button and an LED:

    Button  one leg -> GPIO 17 (pin 11)     the other leg -> GND (pin 9)        (no resistor: the Pi's own pull-up is on)
    LED     GPIO 27 (pin 13) -> 330 ohm -> LED anode (long leg); LED cathode (short leg) -> GND (pin 14)

An LED needs its resistor: a pin gives about 3.3 V and cannot limit the current itself. For something that draws more
than a few mA (a relay board, a buzzer, a motor), a pin cannot drive it directly: use a transistor or a relay board
made for 3.3 V logic, as the motion trap does for its infrared light. Never connect a pin to more than 3.3 V.

**The LED starts off** every time the app starts, and goes off again when it stops, whatever the Toggle was left on:
an output that quietly comes back on after a power cut is not what most things you would switch want. (The Toggle is
not saved, for the same reason.)

**Run it.** Just run it:

    .venv/bin/python apps/gpio_panel.py

The first time, it prints a link and a short code: open the link while you are logged in, approve it, and answer `y`
when the terminal asks you to confirm the account. That makes the Pi yours, and the platform gives it its id. Every run
after that connects straight away. (`pihub setup` does the same linking on its own, if you would rather do that first.)

**No hardware?** `--simulate` uses gpiozero's pretend pins, so it runs on any computer; press "Test press" on the
dashboard to press the pretend button; the Toggle drives a pretend LED. `pip install "thepihub[gpio]"`
if gpiozero is missing (Raspberry Pi OS already has it; a venv made without `--system-site-packages` does not). The pin
driver, `lgpio`, comes from Raspberry Pi OS (`python3-lgpio`) and is found from a venv as well.
"""

from __future__ import annotations

import argparse
import signal
import time
from typing import Any, List, Optional

from pihub import Device, Program


PROGRAM_ID = "gpio-panel"
PRESSED, RELEASED = "Pressed", "Released"
TEST_PRESS_SECONDS = 0.3


class GpioPanel:
    """The dashboard section: a Status for the button, a Toggle for the LED. `button` is a gpiozero `Button`, `led` a gpiozero `LED`
    (or anything with `when_pressed`, `when_released`, `is_pressed` and `on()`, `off()`). Build it before `device.start()`, then call `start()`."""

    def __init__(self, device: Device, button: Any, led: Any, *, simulated_press: Optional[Any] = None) -> None:
        self.device = device
        self.button = button
        self.led = led
        self.program = Program(id=PROGRAM_ID, name="GPIO Panel")

        self.state = self.program.output(id="button", type="Status")
        button.when_pressed = lambda: self.state.set(PRESSED)
        button.when_released = lambda: self.state.set(RELEASED)

        # persist=False: the LED is off at every start, so the Toggle must not remember "on" (see the docstring at the top).
        self.light = self.program.setting("led", "Toggle", default=False, title="LED", persist=False, apply=self._light_changed)

        if simulated_press is not None:
            press = self.program.command(id="test-press", type="Button")
            press.handler(lambda command: self.test_press(simulated_press))
        device.add_program(self.program)

    def start(self) -> None:
        """After `device.start()`: show where the button is now, and make sure the LED is off."""
        self.led.off()
        self.state.set(PRESSED if self.button.is_pressed else RELEASED)

    def close(self) -> None:
        self.led.off()

    def _light_changed(self, value: Any) -> None:
        self.led.on() if value else self.led.off()

    @staticmethod
    def test_press(pin: Any) -> None:
        """Press and release the pretend button, by driving its mock pin the way a real one would go: low while pressed (pull-up wiring)."""
        pin.drive_low()
        time.sleep(TEST_PRESS_SECONDS)
        pin.drive_high()


def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--server", help="the platform to register with the first time (default: $PIHUB_SERVER, else https://thepihub.com); ignored once registered")
    parser.add_argument("--simulate", action="store_true", help="no hardware: pretend GPIO pins, and a Test press button on the dashboard")
    parser.add_argument("--button-pin", type=int, default=17, help="the GPIO the button is wired to, the other leg to GND (default: 17)")
    parser.add_argument("--led-pin", type=int, default=27, help="the GPIO the LED (through its resistor) is wired to (default: 27)")
    return parser.parse_args(argv)


def build(args: argparse.Namespace, transport: Any = None) -> GpioPanel:
    """The device, its button and LED, and the panel, NOT yet started. `transport` is for tests."""
    try:
        from gpiozero import LED, Button, GPIOZeroError
        from gpiozero import Device as Pins
    except ImportError:
        raise SystemExit('error: this app needs gpiozero: pip install "thepihub[gpio]" (Raspberry Pi OS has it for its own Python)')
    from pihub.gpio import PIN_DRIVER_HELP, prepare_pins

    if args.button_pin == args.led_pin:
        raise SystemExit("error: the button and the LED cannot use the same pin")
    if args.simulate:
        from gpiozero.pins.mock import MockFactory

        Pins.pin_factory = MockFactory()
    else:
        prepare_pins()  # a venv without system packages: the pin driver is Raspberry Pi OS's own

    try:
        # At a terminal, the first run links this machine by code and the platform assigns its id; every run after connects at once.
        device = Device(transport=transport, server=args.server)
    except ValueError as error:
        raise SystemExit(f"error: {error}")

    try:
        button = Button(args.button_pin, bounce_time=0.05)  # pulled up by the Pi; pressed = connected to GND; bounce_time ignores contact chatter
        led = LED(args.led_pin)
    except (GPIOZeroError, OSError) as error:
        raise SystemExit(f"error: {PIN_DRIVER_HELP} ({error})")
    return GpioPanel(device, button, led, simulated_press=button.pin if args.simulate else None)


def main(argv: Optional[List[str]] = None) -> None:
    args = parse_args(argv)
    panel = build(args)
    panel.device.start()
    panel.start()
    print(f"{panel.device.id} is online{' (simulated: press Test press on the dashboard)' if args.simulate else ''}. Ctrl+C to stop.")
    signal.signal(signal.SIGTERM, signal.default_int_handler)  # a service stop (systemd) ends the loop like Ctrl+C, so the LED is switched off
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        pass
    finally:
        print("Stopping...")
        panel.close()
        panel.device.stop()
        panel.button.close()
        panel.led.close()


if __name__ == "__main__":
    main()  # pragma: no cover
EOF