How to Add a Power Button to Your Raspberry Pi

So the pi monitors GPIO 3 when in standby mode for signal high to boot, we can add a software routine to monitor for that signal once booted to shutdown. Then it is just a matter of a switch across pins 5&6.

Basically, make two files, one to call the other. add the one that calls the other to the init.d and have it start when booted.

create listen-for-shutdown.py:

#!/usr/bin/env python

import RPi.GPIO as GPIO
import subprocess

GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.wait_for_edge(3, GPIO.FALLING)

subprocess.call(['shutdown', '-h', 'now'], shell=False)

then:
sudo mv listen-for-shutdown.py /usr/local/bin/
sudo chmod +x /usr/local/bin/listen-for-shutdown.py

create another file listen-for-shutdown.sh:

#! /bin/sh

### BEGIN INIT INFO
# Provides: listen-for-shutdown.py
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO

# If you want a command to always run, put it here

# Carry out specific functions when asked to by the system
case "$1" in
start)
echo "Starting listen-for-shutdown.py"
/usr/local/bin/listen-for-shutdown.py &
;;
stop)
echo "Stopping listen-for-shutdown.py"
pkill -f /usr/local/bin/listen-for-shutdown.py
;;
*)
echo "Usage: /etc/init.d/listen-for-shutdown.sh {start|stop}"
exit 1
;;
esac

exit 0

Place this file in /etc/init.d and make it executable.

sudo mv listen-for-shutdown.sh /etc/init.d/
sudo chmod +x /etc/init.d/listen-for-shutdown.sh

Now we’ll register the script to run on boot.

sudo update-rc.d listen-for-shutdown.sh defaults

Since the script won’t be running, we’ll go ahead and start it with:

sudo /etc/init.d/listen-for-shutdown.sh start

Source: How to Add a Power Button to Your Raspberry Pi – Howchoo

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>