Sometimes I need to power off one of my Raspberry Pis, and since I run these computers headless, going to a remote SSH terminal to issue a shutdown command can be extra work. I saw a webpage mentioning using a simple 2 pin jumper to initiate a shutdown script for the Pi. So that’s what I did (green tab on the GPIO pins), I chose python due to the wait_for_edge function.
This script will shutdown the RPi when the tab is pulled. Strangely the RPi will boot if you plug the jumper back in after it has shutdown, or if you pull it out after it has completed shut down (putting it back before it has completed shutting down). If there is no jumper in during boot, then the script will close.
#note crontab for superuser required a new PATH variable as here http://unix.stackexchange.com/questions/43392#answer-43394
import RPi.GPIO as GPIO
print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
GPIO.setup(5, GPIO.IN) #Hardware Pullup on this pin..
ShutdownCommand = ['shutdown', '-h', 'now', '"System halted by GPIO action"']
if GPIO.input(5) == 0:
#run script waiting for jumper removal
KillProcess = subprocess.Popen(ShutdownCommand, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
MountData, MountError = KillProcess.communicate()
Then I simply added this script to the bottom of my root crontab (sudo crontab -e) to run at reboot: