Add a shutdown button to Raspberry Pi

Posted on December 13, 2013 at 5:25 pm

This is the schema I have created to add the button to the Raspi:

raspberry-shutdown-button-schema

I am going to use a simple button, for example:

raspberry-button

I have created a hole on the top part of the Raspi’s box, where I inserted the button:

raspberry-shutdown-button1

This is an image of the button, with the Raspi’s box closed:

raspberry-shutdown-button2

Create a script named start-button-script in /etc/init.d/:

#! /bin/sh
### BEGIN INIT INFO
# Provides:          start-button-script
# Required-Start:    
# Required-Stop:     
# Should-Start:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: script used to execute button-script.bash
# Description:
### END INIT INFO
 
#PATH=/sbin:/bin
 
. /lib/lsb/init-functions
 
case "${1}" in
("start")
    log_action_begin_msg "Starting button-script.bash ...\n"
    nohup /root/button-script.bash >/dev/null 2>&1 &
    log_action_end_msg $?
    exit $?
    ;;
("stop")
    log_action_begin_msg "Stopping button-script.bash ...\n"
    kill -9 `ps aux | grep button-script | awk '{print $2}'`
    log_action_end_msg $?
    exit $?
    ;;
("restart")
    "${0}" stop
    "${0}" start
    ;;
("status")
    ps aux
    ;;
(*)
    log_success_msg "Usage: /etc/init.d/start-button-script {start|stop|restart|status}" >&2
    exit 3
    ;;
esac
 
:

Set the right permissions:

chmod +x /etc/init.d/start-button-script

Create the script used to shutdown the system when the button is pressed:

#!/bin/bash
 
#Define the GPIO path
GPIO="/usr/local/bin/gpio"
 
#Set GPIO mode
$GPIO mode 0 input
 
#Set sleep path
SLEEP="/bin/sleep"
 
#Wait until the button is pressed
while [ `$GPIO read 0` = 0 ]; do
#echo "DEBUG: Button not pressed..."
$SLEEP 1
done
 
#Shutdown the operating system
poweroff

Save the script with the name button-script.bash in the /root/ directory.

Set the right permissions:

chmod +x /root/button-script.bash

To test the script, just run it:

cd /root
./button-script.bash

Now press the button and the system should be shut down.

To start start-button-script everytime the system is booted, type:

update-rc.d start-button-script defaults

That’s all.

Another interesting method used by another user:
Shut down your Raspberry Pi on button press and add reset function

Receive updates via email

Other Posts

Updated Posts