This script is a fork of a script1 by Stewart C. Russell (@scruss). Functionally, it is extremely similar to scruss’s, which allows the user to restart or shutdown a Pi with a single button depending on the time held, but it adds some LED sequences to distinguish between the two options.
By default, holding the button for two to five seconds will restart the Pi, any longer and the Pi will be shut down.
The script itself has been rewritten according to my personal style preferences, thus variables and functions have been renamed and user variables have been relocated to the top of the script. Similarly, I have no personal need for the
systemd service, and therefore I haven’t included it in my repo. That being said, scruss’s
shutdown_button.service can easily be used with this version of the script by changing the
ExecStart line to match your path.
I personally use this script with this illuminated power switch from Adafruit, wiring both the button and the LED to a common ground, using BCM pin 18 (physical pin 12) for the switch, and BCM pin 15 (physical pin 10) for the LED. Pin 15 is pulled low by default, meaning your LED will be completely off when the Pi is shutdown but still receiving power.
To install the script, download or clone it from GitHub. Note that you may need to install the Python 3
gpiozero library, especially if you are running the lite version of Raspbian/Raspberry Pi OS. To have the script run on boot, add
python3 /path/to/pipowerbutton.py & to your
rc.local file, making sure to include the ampersand to fork the process as the script runs in an infinite loop.