LED on and off on a button press using Raspberry Pi Zero
Posted on February 26, 2023 in diy-rpi
Context of the problem:
To re-introduce myself to electronics, I started from the simplest of experiments - turn an LED on/off on the press of a button.
I came across this article by Ian Buckley on MUO - Technology Simplified and found this really easy to do. I had some modifications because I used a mini breadboard.
Hardware components used:
- Raspberry Pi Zero W,
- a mini breadboard,
- a button,
- a 220 Ohm resistor,
- an LED,
- jumper wires
Software used:
- Raspbian OS,
- Python 3 (and signal package),
- GPIO Zero.
- Raspberry Pi Imager
Solution:
A few steps to complete before your Raspberry Pi is ready:
Raspberry Pi must be connected to a power supply and internet. The power source should be able to provide at least 1 Amp of current. The Raspberry Pi Zero W requires at least 1 Amp of current to run. Flash the Raspberry Pi with the latest version of Raspbian OS. Create a user and configure ssh so that you can develop projects on a laptop and connect to Pi in headless mode.
Hardware setup:
Once the Raspberry Pi is up and running, get the mini breadboard. These mini breadboards do not have a marked power rail. I used the top row of one of the sides as the positive and the other side as negative. Next steps are easy: Since there is no soldering involved, I placed the Raspberry Pi on a tiny piece of styrofoam, so the jumper wires stay in place.
- Connect one of the 5V pins on the Raspberry Pi to the positive rail of the breadboard. Use a jumper wire.
pinoutcommand outputs the pin details:

- Connect one of the GND (ground) pins on the Raspberry Pi to the negative rail of the breadboard.
- Place the button in the middle of the mini breadboard. One side of the button is connected to the ground row, and the other side is connected to GPIO pin 16. Make sure the button is connected to the positive rail on both sides - this may not be needed on a full size breadboard.
- Place the LED on the mini breadboard. The positive side (the longer leg) of the LED is connected to pin 12 (GPIO 18).
- Place the 220 Ohm resistor on the mini breadboard. The resistor is connected between the negative side of the LED and the ground rail. Once everything is connected, the LED should be lit up. If not, check the connections.
Software setup:
- SSH into the Pi from computer.
- Create a new directory called
led-buttonand create a new file calledled-button.pyin the directory. - Add the following script:
from gpiozero import LED, Button
from signal import pause
led = LED(18)
button = Button(23)
button.when_pressed = led.on
button.when_released = led.off
pause()
- Run the script using
python3 led-button.pycommand. - Press the button and the LED should turn off. Release and it will be on.

References:
- https://www.makeuseof.com/tag/add-button-raspberry-pi-project/