Safe Power Down
Setting up an OS service to shut down the Raspberry Pi requires two short scripts and registering the shell to run at startup:
- A short python script to
- Set up a GPIO pin to wait to be pulled to ground.
- When grounded, run the shutdown command.
- A shell script to set the python script as a service
- Write the two files, and then use super user privileges (sudo) to:
- Move files to the correct directory (sudo mv FileName NewDirectory)
- Make the files executable (sudo chmod +x Filename)
- Register the shell script (sudo update-rc.d listen_for_shutdown.sh defaults)
The python script, listen_for_shutdown.py
- Sets up GPIO pin 20 as an input with an internal pull-up resister
- Waits for GPIO pin 20 to "fall" to ground
- Execute the shutdown command.
The shell script listen_for_shutdown.sh sets up the python script as a service during start up with two required functions
- start) Run the python script in the background (a service) waiting for pin 20 to be grounded.
- stop) "Kill" the python script, service, when the system is shutdown or put to sleep.
GPIO pin 20 is connected to the on-off-on momentary rocker switch next to the green LED on the Monitor bracket. Also see the PWM HAT for accessing GPIO pin 20.