Wednesday, January 6, 2016

Shutdown button

It's nice that the Raspberry Pi automatically starts up as soon as you plug in power but since you are running Linux, you really shouldn't just unplug it if you want to shut it down. Minimally, the right thing to do is to issue a shutdown command and let the system fully shut down before disconnecting the power. I wanted to build a simple switch to act as a power button to initiate shutdown as soon as I press it.


The simplest solution is to connect a momentary switch to one of the GPIO ports and run the shutdown command when you detect that the button is pressed. In the circuit depicted above I've connected GPIO port 40 on the board to ground on port 39 through a momentary switch. The code sets up port 40 as an input port and then uses the add_event_detect function to trigger the shutdown_now function if it sees a "falling edge" event. A falling edge is when the voltage drops which in this case is triggered by connecting port 40 to ground when the button is pressed.

https://github.com/steguis/hapiprojects/blob/master/powermgr/powerswitch.py

This script isn't very useful if it isn't running so to make sure it runs when the Raspberry Pi starts up, we're going to add a cron job to trigger this on startup.
sudo bash
crontab -e
 Add the following line and save (this assumes that the script is saved in /usr/local/etc)
@reboot sudo python /usr/local/etc/powerswitch.py
 Run cron:
sudo /etc/init.d/cron start
Reboot the Raspberry pi and check that the script actually triggered:
ps aux | grep -i powerswitch.py
 It should return something like this indicating that it is running:
root       478  0.0  0.0   1896   392 ?        Ss   22:07   0:00 /bin/sh -c sudo python /usr/local/etc/powerswitch.py
root       479  0.0  0.3   6600  3132 ?        S    22:07   0:00 sudo python /usr/local/etc/powerswitch.py
root       509  0.0  0.5  17240  5076 ?        Sl   22:07   0:00 python /usr/local/etc/powerswitch.py
pi        1001  0.0  0.2   4264  1964 pts/0    S+   22:29   0:00 grep --color=auto -i powerswitch.py
 Now if you push the button the Raspberry Pi should immediately initiate the shutdown.