A button toggles an LED with gpiozero on a Raspberry Pi 4
gpiozero on a Raspberry Pi 4: each press of a button on GPIO2 turns the LED on GPIO17 on or off, with when_pressed and signal.pause(). The whole build, a Raspberry Pi 4 and 3 more parts, runs here in your browser on the Python below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $58. On Mokxi they're free.
The code
The Python exactly as the editor opens it. Change a line there and press Run: the board runs main.py in a Python engine in the page, with gpiozero and RPi.GPIO, and nothing to compile.
# A button toggles an LED, with gpiozero.
# The button is between GPIO2 (pin 3) and ground: GPIO2 has the board's own
# 1.8 k pull-up, and Button() turns the pad's pull-up on as well.
from gpiozero import Button, LED
from signal import pause
led = LED(17)
button = Button(2, bounce_time=0.05) # ignore 50 ms of contact bounce
def toggle():
led.toggle()
print("LED is", "on" if led.is_lit else "off")
button.when_pressed = toggle
pause() # wait for presses for ever; Ctrl-C in the Serial Monitor stops it
Parts list
5 parts, plus the jumper wires. They retail for about $58; on Mokxi they're free.
- 1 × Raspberry Pi 4 Model B
- 1 × Half breadboard
- 1 × Resistor, 330 Ω
- 1 × LED, green
- 1 × Pushbutton
How it is wired
5 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Raspberry Pi 4 Model B pin GPIO2; Pushbutton pin 1a; Pushbutton pin 1b
- Ground: Raspberry Pi 4 Model B pin GND; Pushbutton pin 2a; Pushbutton pin 2b
- Ground: Raspberry Pi 4 Model B pin GND; LED, green pin C
- Raspberry Pi 4 Model B pin GPIO17; Resistor, 330 Ω pin 1
- Resistor, 330 Ω pin 2; LED, green pin A
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.