How to add shutdown switch to Raspberry Pi


There is no on/off switch on Raspberry Pi. Once you install your lights outside, it may be outside the wireless range to shut it down from terminal. Simply yanking off power cable will corrupt the OS; so we need to add on/off switch. We will be using a script written by Inderpreet Singh that uses a GPIO pin to send a shutdown command to Raspbian OS.

Create a directory called ‘myscript’ in the home folder of the Pi (of course, you have to ssh into Pi)

mkdir myscript

Then cd to this directory:

cd myscript

And create a file:

nano shutpi.py

Copy the following lines into that empty file:

 # 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.setup(21, 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(21, GPIO.FALLING, callback = Shutdown, bouncetime = 2000)
 # Now wait!
 while 1:

Save and close the file. Stay inside the ‘myscript’ directory and set this script to run as root:

sudo python shutpi.py

We now need to set the script to run as system boot:

sudo nano /etc/rc.local

There add the following line between ‘fi’ and ‘exit 0’ line:

sudo python /home/pi/myscript/shutpi.py &

So it looks like this:

# Print the IP address
 _IP=$(hostname -I) || true
 if [ "$_IP" ]; then
 printf "My IP address is %s\n" "$_IP"
 sudo python /home/pi/myscript/shutpi.py &
 exit 0

Shut down your system and connect a push button to GPIO pin 21 and GND using male-female breadboard cable.

Reboot your system and when you push the button; your system should shut down.

Don't miss out great stories, subscribe to our newsletter.

Apple’s latest invention: password-less root access

Previous article

Best Christmas Gifts for your techie child

Next article
Login/Sign up