One thing that sometimes bothers me when using an headless embedded Linux system, is the workload I get when I need to power off the system for some hardware maintenance (e.g. adding some sensor, replacing some peripheral, moving the system to another location). Indeed, one cannot just cut the power supply; there is the risk that some files become corrupted. So, the proper way to shutdown a Linux system is to send a command like:
$ shutdown -h now
But to do this, one needs to be “online” with the system, via SSH for example, using another system (computer) that, at that moment, may precisely be OFF… Doh!
So, at the expense of a simple push-button (normally open), a couple of wires and some programming, I implemented a smart(?) way of shutting down my Raspberry Pi, safely, without the need of an extra computer, SSH and other complications.
Connecting the push-button
The push-button is connected to two of the 26 or 40 pins header, depending on the version of the raspberry Pi in use. From those two pins, one is GND and the other may be any free GPIO. Remember that some pins have multiple possible roles (I2C, UART, SPI, etc), so choose wisely. In my case, I plugged the button between pins 14 and 16, respectively GND and GPIO23.
Programming
To translate any action on the push-button into a Shutdown command, a script was written in the Pi’popular Python programming language.
In a folder of your choice (e.g., /home/pi), using the terminal command line, enter:
$ nano shutdown_button.py
Then, copy the following code into it and save as usual (CTRL-X + Y + ENTER):
Testing the script
To test this script, just enter the following command and then press the button once.
$ sudo python shutdown_button.py
If everything is correct, the system should shutdown itself. You must then unplug and replug the power cord to start your system again.
Launching this script automatically after every system power-up
In order to launch this script automatically after every system boot, one must add the following line to the /etc/rc.local file (just before the line with exit 0) as shown in the image hereafter (assuming your script file is in the /home/pi folder):
python /home/pi/shutdown_button.py &
Final notes
- If you prefer to have your Pi to reboot instead of shutting down after pressing the button, in the shutdown_button.py script, in the line containing os.system(“shutdown -h now”), replace the letter ‘h‘ (from halt) by a ‘r‘ (for reboot).
- The line stated in the above note is in fact a System Call. So, with this script, you can have your Pi doing “anything you want” after pressing the push-button, just by replacing the command between quotation marks, by another command invoking some application that suit your needs.
Have fun!