This is for adding a power switch on a RaspberryPi to trigger a script to turn off or reboot.
Information on this page was obtained from here.
This page was created for my ease of access.
Use information from this page at your own discretion.
- RaspberryPi
- Momentary switch
- Adequate wiring
Attach the momentary switch via wiring to GPIO pin 5 and 6 on the RaspberryPi Here's a few references
sudo apt install python3-rpi-lgpio -y
sudo nano /usr/local/bin/power-switch.py
import threading, subprocess
import RPi.GPIO as GPIO
if __name__ == '__main__':
try:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5, GPIO.IN)
GPIO.wait_for_edge(5, GPIO.RISING)
pin = GPIO.wait_for_edge(5, GPIO.FALLING, timeout=3000)
if pin is None:
subprocess.call('sudo shutdown -h now', shell=True)
else:
subprocess.call('sudo reboot', shell=True)
finally:
GPIO.cleanup()
What this does
- Push and hold for > 5 seconds shutdown the RaspberryPi
- Push and hold for < 5 seconds reboots the RaspberryPi
sudo nano /etc/rc.local
Add a line before exit 0
to execute the script at boot.
python /usr/local/bin/power-switch.py &
Be sure to test that it is functional.