Raspberry Pi Shutdown Switch – Safely Turning off the Pi

We use a model B rev 2.0 Raspberry Pi as one of our Samba and DLNA media servers, and normally turn it off through a Webmin control panel to ensure nothing untoward happens with any of the attached hard drives. This solution is less than ideal however, as it requires a second powered-on device and a couple of clicks to get to the shutdown page in the control panel.

The Raspberry Pi forum has am excellent thread about a simple & safe shutdown button, from which I copied to produce my shutdown switch. It’s something you can put together in less than 20 minutes if you have the parts.

All you need is to install the RPi.GPIO Python class on the Pi (use SSH to grab it, “wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.4.1a.tar.gz”; unzip it; and install it, “sudo python setup.py install”; then remove the files to tidy it all up), and you can start accessing the pins via Python scripts.

Just connect pin 1 to a momentary open switch, and the switch to a 1K and a 10K resistor. Then connect the 10K resistor to the ground on pin 9 and the 1K to pin 11 (GPIO17). If you’re wondering where these are then this page has some nice illustrations; and more info on these pins can be found here. It’s worth covering the 5V line with some insulation just to minimise the risk of shorting out your Pi with it (see images below), as everything else on the GPIO header is 3.3V.

Breadboard setup, minus switch which would cross lanes 12 & 13.
Breadboard setup, minus switch which would cross lanes 12 & 13.
Raspberry Pi Shutdown Switch
In the case, soldered directly onto the pins with a momentary switch screwed into the case above the pi logo (hence minimising risk of contact)

All that’s left is to monitor pin 11 (GPIO17) for activity, for which I used the code on the Raspberry Pi forum.

Placed in /home/pi/bin/button/shutdown.py

import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
while True:
if(GPIO.input(17)):
os.system("sudo shutdown -h now")
break
time.sleep(1)

Placed in /etc/rc.local on the line before “exit 0”

python /home/pi/bin/button/shutdown.py

Then the Pi will shutdown when the button is pressed for about 1 second – only the Power light will remain on (red) when it’s shut down. It’s worth noting that this won’t work if the Pi has crashed but that’s not an issue we often see.

Updated 22/01/15 – Thanks to “Joost” for clarification on pins, specifically that GPIO17 is pin 11 on the board.