Posted on December 13, 2013 at 5:25 pm
This is the schema I have created to add the button to the Raspi:
I am going to use a simple button, for example:
I have created a hole on the top part of the Raspi’s box, where I inserted the button:
This is an image of the button, with the Raspi’s box closed:
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
Other Posts
- Route OpenVPN Connections Through Floating IP
- How to Configure a Floating IP in a VPS (Hetzner)
- Set OpenVPN to Listed on a Specific IP Address
- Bash Trim Leading and Trailing Whitespace from a String
- Bash Get Name of Ethernet Network Interface
- VPN Providers with Dedicated Static IP Address
- OpenVPN Iptables Rules
- WireGuard VPN Iptables Rules
Updated Posts
- AMD Chipsets & Graphics Card Drivers for Windows 7, 8, 10
- AMD Radeon 7400 Drivers for Windows 10
- How to pass custom command-line parameters in InnoSetup
- Add Desktop shortcut for all Windows PC users
- Programmatically create desktop icon with InnoSetup
- GeneratePress - a Lightweight WordPress Theme 2021
- InnoSetup disable DesktopIcon via command-line
- Use cURL to authenticate with JWT Bearer tokens