There's this GPIOZERO shutdown method that let's you specify a "hold_time" but I want a more immediate shutdown response instead of waiting for a few seconds.
Code: Select all
from gpiozero import Button
from subprocess import check_call
from signal import pause
def shutdown():
check_call(['sudo', 'poweroff'])
shutdown_btn = Button(17, hold_time=2)
shutdown_btn.when_held = shutdown
pause()
So here's how you do it.
1. Change the value of gpio_pin1 and gpio_pin2 to your own GPIO pins that correspond to the two buttons you want to use. Copy and save it to /home/pi as shutdown.py.
Code: Select all
import RPi.GPIO as GPIO
from subprocess import check_call
import time
GPIO.setmode(GPIO.BCM)
gpio_pin_1 = 13
gpio_pin_2 = 23
GPIO.setup(gpio_pin_1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(gpio_pin_2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
TD = 0.2
gpio_pin_1_ptime = 0
gpio_pin_2_ptime = 0
def shutdown():
if (abs(gpio_pin_1_ptime - gpio_pin_2_ptime)) < TD:
check_call(['sudo', 'poweroff'])
def btn_func(b):
if b == 1:
global gpio_pin_1_ptime
gpio_pin_1_ptime = time.time()
if b == 2:
global gpio_pin_2_ptime
gpio_pin_2_ptime = time.time()
shutdown()
GPIO.add_event_detect(gpio_pin_1, GPIO.FALLING, callback=lambda x: btn_func(1), bouncetime=500)
GPIO.add_event_detect(gpio_pin_2, GPIO.FALLING, callback=lambda x: btn_func(2), bouncetime=500)
while 1:
time.sleep(10)
Code: Select all
sudo python /home/pi/shutdown.py &