Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท GPIO and Python

Buttons and Digital Input

Read a push button on the Raspberry Pi with gpiozero: wiring, pull-up resistors, polling versus events, debouncing, and controlling an LED with a button.

An LED shows that the Pi can talk to the world. A button shows that the world can talk to the Pi. Reading digital inputs is the base of almost every interactive project: doorbells, game controllers, limit switches, alarm contacts. The idea is simple, but real buttons have a few quirks, floating pins and bounce, that this lesson teaches you to handle.

Wiring a button

A push button is a switch with four legs that act as two pairs; pressing it connects them. For a Pi, wire one side to a GPIO pin (we use GPIO4 on physical pin 7) and the other side to ground. No external resistor is needed, because the Pi can switch on an internal pull-up.

With a pull-up, the pin reads high when the button is open, because the resistor holds it at 3.3 V. Pressing the button connects the pin to ground and it reads low. So the logic is inverted: low means pressed. gpiozero hides this and gives you is_pressed.

flowchart LR
  A["3.3 V"] --> B["internal pull-up resistor"]
  B --> C["GPIO4 (pin 7)"]
  C --> D["button"]
  D --> E["GND"]

Open: the pin sees 3.3 V (high). Pressed: it is connected to ground (low).

Reading the button

The real code with gpiozero (read-only):

Python
from gpiozero import Button
from time import sleep

button = Button(4)          # pull-up is the default

while True:
    if button.is_pressed:
        print("pressed")
    sleep(0.1)

This is polling: your program asks again and again. It is easy but wastes time and can miss a quick press. The better way is events. Attach a function and let the library call it:

Python
from gpiozero import Button
from signal import pause

def say_hello():
    print("Hello!")

button = Button(4)
button.when_pressed = say_hello
button.when_released = lambda: print("Bye!")
pause()

You can also wait for a press: button.wait_for_press() blocks until the button is pressed. Options include hold_time and when_held for long presses, and bounce_time to filter noise. For a wiring that uses an external pull-down, create Button(4, pull_up=False).

Bounce

A mechanical switch does not close cleanly. For a few milliseconds the metal contacts bounce, producing a burst of on/off flickers. A program that counts changes might see five presses for one push. Debouncing ignores changes that arrive too soon after the previous one. gpiozero can do it for you with bounce_time=0.05.

The stand-in below simulates a bouncing signal and counts presses with and without a debounce filter.

Python Stand-in: counting presses with debounce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without filtering the counter reports several presses for one real push; with a 20 ms window it reports one, which is what you want.

A button controls an LED

Combine input and output. The classic program lights an LED while the button is held. With gpiozero it is one line (read-only):

Python
from gpiozero import LED, Button
from signal import pause

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

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

Notice there is no loop. You describe what should happen and the library reacts. The next stand-in builds the same behavior with small simulated classes, including an event callback, so you can see the pattern working.

Python Stand-in: button events driving an LED

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Counting and toggling

A common beginner project makes a button toggle an LED: one press on, the next press off. Because the callback fires only on the press, the code is short:

Python
from gpiozero import LED, Button
from signal import pause

led = LED(17)
button = Button(4, bounce_time=0.05)
button.when_pressed = led.toggle
pause()

Other input devices behave the same way: a toggle switch, a magnetic door contact, a tilt switch, a float switch in a water tank. gpiozero also offers DigitalInputDevice for generic inputs and MotionSensor and LineSensor for specific parts.

Common mistakes

  • Reading a floating pin. Always use a pull-up or pull-down; gpiozero does it by default for Button.
  • Forgetting that pressed is low when you use raw pin reads.
  • Blocking forever in a while loop without a short sleep, which uses 100 percent CPU.
  • Skipping debounce on noisy switches.
  • Connecting a button to 5 V and a GPIO pin. Always use 3.3 V or ground.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With the Pi's internal pull-up and the button wired to ground, what does the pin read when the button is pressed?

    Pressing connects the pin to ground, so it reads low; gpiozero reports is_pressed as True.
  2. 2. What is switch bounce?

    Contacts vibrate for a few milliseconds, creating several false edges.
  3. 3. Why use button.when_pressed instead of polling in a loop?

    An event handler runs only when the state changes, so the program can sleep in between.
  4. 4. What does a floating input pin do?

    Without a defined level the input picks up noise; use a pull resistor.

Summary

  • A button wired between a GPIO pin and ground uses the internal pull-up; pressed reads low.
  • gpiozero offers is_pressed, when_pressed, when_released and bounce_time.
  • Events beat polling: they react instantly and use little CPU.
  • Debounce noisy switches, and always give inputs a defined level.

Next: PWM: Dimming and Servos