- Cut a female-female jumper cable in half.
- Strip the ends and solder each to one pin on one side of the button.
- Clip off the pins on the other side of the button.
- Plug ends into 1 ground and 1 GPIO pin on your pi. I used GPIO #12 & the ground next to it.
Thanks to Alex Glow and this script here, I modified this existing script for my pi.
(I created this program by typing touch shutdown_pi.py
, then opening the file: sudo nano shutdown_pi.py
and pasting the following code and saving it (CTRL+X).
python
#!/bin/python
# Simple script for shutting down the raspberry Pi at the press of a button.
# by Inderpreet Singh
import RPi.GPIO as GPIO
import time
import os
# Use the Broadcom SOC Pin numbers
# Setup the Pin with Internal pullups enabled and PIN in reading mode.
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.IN, pull_up_down = GPIO.PUD_UP)
# Our function on what to do when the button is pressed
def Shutdown(channel):
os.system("sudo shutdown -h now")
# Add our function to execute when the button pressed event happens
GPIO.add_event_detect(12, GPIO.FALLING, callback = Shutdown, bouncetime = 2000)
# Now wait!
while 1:
time.sleep(1)
We want this program to run on boot and run in the background so that when the button is pressed, the program will trigger the shutdown script to run. You can trigger programs to run at boot a few diff ways on the pi, but I already use cronjobs, so I edited that file.
- Run
crontab -e
(if it's your first time, I'd choose option 2 and use nano to edit the file). - At bottom of the file, add
@reboot python /home/pi/shutdown_pi.py &
(Tip: the & at the end tells the pi to run the program in the background) - Press CTRL+X to save & exit.
- Run
sudo shutdown -r now
to reboot the pi. - Press the button after it reboots and it should safely shutdown the pi now! 🎉