Push buttons and switches are very important part of any electronic device. You use it daily to turn on Lights to mobile phone. It is everywhere. There are various type of push button two leg and four leg. But we will use four leg push button for this tutorial. In short this tutorial is about, when you press button it will turn ON LED, when you release button it will turn OFF LED. So let’s get started.

For making this project, you will need,

  1. Raspberry pi 4,
  2. Dual Fan Heat Sink aluminium Armor Case. (Optional)
  3. Push Button,
  4. microSD card,
  5. Power adapter,
  6. 220 ohms Resistor,
  7. LED,
  8. Breadboard,
  9. Jumper Wire.
Circuit for push button with Raspberry Pi 4:

Do connection as shown in diagram.

circuit for Push Button with Raspberry pi 4
Python Script for Push Button with Raspberry pi 4:
from gpiozero import LED, Button
from signal import pause

led = LED(25)
button = Button(2)
button.when_pressed = led.on
button.when_released = led.off
pause()
Script Explanation:

This code it self explanatory. But I will explain it briefly.

First we will import LED and Button from gpiozero library. As we are going to work with these two.

from gpiozero import LED, Button

Now we are importing pause from signal. We are importing this because when python reaches end of script it will terminate the process. “Pause” will keep script alive.

from signal import pause

Here we are creating LED object called led that refer to GPIO 25 and Button object called button that refer to GPIO 2.

led = LED(25)
button = Button(2)

When button is pressed it will turn ON LED.

button.when_pressed = led.on

When button is released it will turn OFF LED.

button.when_released = led.off

As I explain earlier we want to keep script alive so we are using pause

pause()

In next tutorial, I will show, how to debounce push button in raspberry pi 4. so that we can push only once it will turn ON and push one time again to turn off. We don’t need to hold the button to keep light lit.

Till then Keep Learning Keep Making.