Fast delivery
Discount conditions for companies
Up to 10% discount for pupils, students and educational institutions
Europe wide shipping for 4,90€

Button on the Raspberry Pi

In the first examples we got to know the GPIO pins as outputs, which we switched to HIGH to let an LED light up. But GPIO stands for General Purpose Input/Output. So you can also program the pins as input. Then it can be determined whether there is a voltage at the input (HIGH) or not (LOW). The Raspberry Pi has only digital inputs (a workaround for measuring analog voltages we will get to know later), nevertheless the applied voltage does not have to be exactly 3.3V to be recognized as HIGH, and not 0V to be recognized as LOW. Up to about 1.4V is recognized as LOW, everything above 1.9V is surely recognized as HIGH. The only problem is the small range around ½ of 3.3V and a free pin with nothing connected to it.

We will get to know several digital sensors which should trigger an alarm or a certain action in our program (e.g. motion detector). The simplest of these sensors is the button, a spring-loaded switch that closes a circuit when the button is pressed and opens it again when the button is released.

If we connect one contact of the button to a GPIO pin and the other to 3.3V, the signal HIGH is clearly detected when the button is pressed. The problem starts after the button is released. What is the state of the GPIO then? An undefined one! You can't program with it. In the switched off state the GPIO should be permanently at GND potential. But this would lead to a short circuit when the button is pressed. Remedy is a resistor, which must be so large that only a small current flows. Resistors of 4.7 k (=4700 ohms) or 10 kΩ (=10,000 ohms) are common. These resistors are called pull-down resistors.

But you can also program the GPIO so that it normally indicates HIGH and recognizes the key press against GND as a change to LOW. Then the resistor is called pull-up resistor. And to make it even more confusing for beginners, the Raspberry Pi GPIOs have an internal pull-up or pull-down resistor that can be enabled or disabled in the program. Fortunately, this makes the initial circuits very simple.

The circuit diagram: Push button on the Raspberry Pi

Button on the Raspberry Pi

Fritzing: Button on the Raspberry Pi

The program code: Push button on the Raspberry Pi

from gpiozero import LED, Button
from signal import pause
led = LED(12)
button = Button(16)
button.when_pressed = led.on
button.when_released = led.off
pause()

From the module gpiozero, the classes LED and button are imported, separated by commas, then the objects led and button are instantiated with their respective GPIO numbers.
Instead of the sleep()-Function from the module time module, pause from the module signal sleep() would mean complete standstill, the keystroke would not be noticed in the time. Without pause() the program would terminate and nothing would happen.
The instantiation of button was very simple, because we only specified the GPIO number and otherwise used the default settings (see class definition next line). If you want to deviate from this, you have to enter additional parameters as keyword arguments.

class gpiozero.Button(pin, *, pull_up=True, active_state=None, bounce_time=None,
hold_time=1, hold_repeat=False, pin_factory=None)

More details about gpiozero can be found here.

Extension of the experimental setup: A traffic light cycle is to be started with a Raspberry Pi when a button is pressed.

The experimental setup is based on the first example. Instead of a LED, the LED traffic light is used. This has built-in series resistors. We instantiate three LED objects and define a function trafficLight, which is called when a button is pressed.

The program code: Traffic light cycle on Raspberry Pi

from gpiozero import LED, Button
from signal import pause
from time import sleep
redled = LED(16)
yellowled = LED(20)
greenled = LED(21)
button = Button(12)
def trafficLight():
redled.on()
sleep(1)
yellowled.on()
sleep(1)
greenled.on()
redled.off()
yellowled.off()
sleep(1)
yellowled.on()
greenled.off()
sleep(1)
redled.on()
yellowled.off()
sleep(1)
redled.off()
button.when_pressed = trafficLight
pause()

Extension: Reaction game with two buttons on Raspberry Pi

You need two buttons, a buzzer and a red and a yellow LED. After starting the Reaction Game, the yellow LED lights up first. With time = uniform(5, 10) the red LED lights up after a random time between five and ten seconds. Then two players can each press their button as fast as possible. Whoever presses too early will be caught cheating, the buzzer will sound for half a second.

The program code: Reaction buzzer with two buttons on the Raspberry Pi

#! /usr/bin/python3
# Reaction Game - push button, when red LED lights-up
# based on gpiozero documentation, Basic Recipes
# enhanced to recognize cheating by Bernd Albrecht
# Red LED lights-up 5 - 10 sec after the yellow LED
from gpiozero import Button, LED, Buzzer
from time import sleep
from random import uniform
from sys import exit
led_red = LED(16)
led_yellow = LED(20)
buzzer = Buzzer(12)
player_1 = Button(23)
player_2 = Button(18)
led_yellow.on()
time = uniform(5, 10)
sleep(time)
if player_1.is_pressed:
print("Player 1 is cheating!")
buzzer.on()
sleep(0.5)
buzzer.off()
led_yellow.off()
exit()
if player_2.is_pressed:
print("Player 2 is cheating!")
buzzer.on()
sleep(0.5)
buzzer.off()
led_yellow.off()
exit()
led_red.on()
led_yellow.off()
while True:
if player_1.is_pressed:
print("Player 1 wins!")
break
if player_2.is_pressed:
print("Player 2 wins!")
break
led_red.off()
Please enter the string in the text field below.

The fields marked with * are required.

Matching articles
100 pieces - LEDs with 5mm diameter (5 colors) 100 pieces - LEDs with 5mm diameter (5 colors)
Content 1 Piece
€1.97 *
Item no: F23107316
Add
- 5%
Push-button small, with round knob Push-button small, with round knob
Content 1 Piece
€0.25 * €0.26 *
Item no: F23106728
Add
- 5%
KY-004 Push-button on circuit board KY-004 Push-button on circuit board
Content 1 Piece
€1.17 * €1.23 *
Item no: F23106815
Add
- 5%
Pushbutton assortment 10x20 pieces 6mm base Pushbutton assortment 10x20 pieces 6mm base
Content 1 Piece
€6.32 * €6.65 *
Item no: F23107190
Add
Breadboard (plug-in board) with 830 contacts Breadboard (plug-in board) with 830 contacts
Content 1 Piece
€2.22 *
Item no: FUN-1010553
Add