How To Shutdown Your GBZ By Pressing Two Buttons
Posted: Tue Jul 11, 2017 9:40 pm
I've been searching for a way to shutdown my GBZ using two GPIO buttons but couldn't find any solution online that does not eat too much CPU performance.
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.
My solution is to use two GPIO buttons that you press at the same time to issue a shutdown. I have tried GPIOZERO's "is_pressed" function but it consumes too much CPU and wasn't sure how to do it properly.
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.
2. Edit the file /etc/rc.local and add the following before the line exit 0 and save. Reboot your GBZ. The script should now work systemwide.
Update: Code uses native RPi.GPIO so you don't have to install any additional packages.
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 &