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 bashAdd the following line and save (this assumes that the script is saved in /usr/local/etc)
crontab -e
@reboot sudo python /usr/local/etc/powerswitch.pyRun cron:
sudo /etc/init.d/cron startReboot the Raspberry pi and check that the script actually triggered:
ps aux | grep -i powerswitch.pyIt 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.pyNow if you push the button the Raspberry Pi should immediately initiate the shutdown.
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

No comments:
Post a Comment