Skip to content

Instantly share code, notes, and snippets.

@traumverloren
Last active February 18, 2024 23:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save traumverloren/734839dbe8cd7e4865baddcff970b278 to your computer and use it in GitHub Desktop.
Save traumverloren/734839dbe8cd7e4865baddcff970b278 to your computer and use it in GitHub Desktop.
Raspberry Pi GPIO Shutdown button

Create a safe way to shutdown a headless raspberry pi with a tiny button.

1. Make the button:

  • 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.

2. Write a program for the button:

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)

3. Create a cronjob:

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.

4. Test it!

  • Run sudo shutdown -r now to reboot the pi.
  • Press the button after it reboots and it should safely shutdown the pi now! 🎉
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment