Thursday, June 11, 2020

Raspberry PI: Shutdown with momentary switch

Connect N.O. (normally open) momentary switch to pins 39 and 40 on the GPIO pins.

Run commands:
sudo apt update
sudo apt install python3-gpiozero
sudo nano shutdown-press-simple.py
Copy and paste the following text into the file you just created:
#!/usr/bin/env python3

from gpiozero import Button

import os

Button(21).wait_for_press()

os.system("sudo poweroff")
Run commands:
sudo chmod a+x shutdown-press-simple.py
sudo nano /etc/rc.local
Add the following text above "exit 0":
sudo python /home/pi/shutdown-press-simple.py &
Reboot and test the button.