Raspberry Pi Shutdown Button

Every now and again I build a headless Pi project, not all of which are required or can stay powered on all of the time so I need a way of shutting the device down before cutting the power to it.

A simple Python script can be used to detect a signal via a GPIO pin and when receiving it initiate the shutdown command, it’s then a simple matter of waiting for a few seconds before killing the power. Everything is shutdown neatly and the chances of corrupting the SD card are significantly reduced.

save the following as shutdown.py

#! /usr/bin/python

import os
import time
import RPi.GPIO as GPIO
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)
def Shutdown(channel):
 os.system("sudo shutdown -h now")
GPIO.add_event_detect(18, GPIO.FALLING, callback = Shutdown, bouncetime = 2000)
while 1:

Now we have our script we can test it out by simply running the following command

sudo python shutdown.py

Now short GPIO 18 (pin 12) to GND and watch as your Pi begins it’s shutdown process.

Now we want to get the script to run every time the Pi is booted up so that it’s sitting there waiting for the signal to shutdown your device, for this we need to create a shell script that will start the Python script with root access. Put the shell script in the same directory as your shutdown.py script.

save the following as shutdown.sh

cd /
cd home/pi
sudo python shutdown.py

Lets test the shell script

sudo chmod 755 /home/pi/shutdown.sh

To make the script executable then

sudo sh /home/pi/shutdown.sh

To run it, again if you short GPIO 18 (pin 12) to GND your Pi should begin it’s shutdown process.

Now we are going to use crontab to autostart the script. You are going to want to open the crontab editor under the root user by using the following command;

sudo crontab -e

Append the following line to the end of the file

@reboot sh /home/pi/shutdown.sh

That’s it your about done, stick a push to make switch between GPIO 18 (pin 12) and GND and you have a very simple shutdown button for your Pi


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *