From 5a7edff3b4438aa59680a4f8dcdf42a28e098d8e Mon Sep 17 00:00:00 2001 From: Fabio Nisci Date: Tue, 10 Nov 2020 17:51:10 +0100 Subject: [PATCH 1/2] added a status led, GPIO.add_event_detect and debounce to better handle timeouts and false positive --- listen-for-shutdown.py | 50 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) mode change 100755 => 100644 listen-for-shutdown.py diff --git a/listen-for-shutdown.py b/listen-for-shutdown.py old mode 100755 new mode 100644 index cecc42b..9d8f5ad --- a/listen-for-shutdown.py +++ b/listen-for-shutdown.py @@ -1,12 +1,52 @@ #!/usr/bin/env python - +import signal +import sys import RPi.GPIO as GPIO import subprocess +import time + +PWR_BUTTON_GPIO = 3 # 9(GND) 5-GPIO3(+) +RST_BUTTON_GPIO = 4 # 9(GND) 7-GPIO4(+) +LED_STATUS_GPIO = 18 # 6(GND) 12-GPIO18(+) +DEBOUNCE_TIME = 300 + +# DEBUG +# if __name__ == '__main__': +# GPIO.setmode(GPIO.BCM) +# GPIO.setup(PWR_BUTTON_GPIO, GPIO.IN) +# pressed = False +# while True: +# # button is pressed when pin is LOW +# if not GPIO.input(PWR_BUTTON_GPIO): +# print("Button pressed!") +# else: +# print("Button not pressed!") +# time.sleep(0.5) + +def signal_handler(sig, frame): + # print("Cleanup and exit...") + GPIO.cleanup() + sys.exit(0) +def button_power_pressed_callback(channel): + # print("POWER BUTTON PRESSED!") + subprocess.call(['shutdown', '-h', 'now'], shell=False) -GPIO.setmode(GPIO.BCM) -GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP) -GPIO.wait_for_edge(3, GPIO.FALLING) +def button_reboot_pressed_callback(channel): + # print("REBOOT BUTTON PRESSED!") + subprocess.call(['shutdown', '-r', 'now'], shell=False) -subprocess.call(['shutdown', '-h', 'now'], shell=False) +if __name__ == '__main__': + GPIO.setmode(GPIO.BCM) + + GPIO.setup(LED_STATUS_GPIO, GPIO.OUT) + GPIO.setup(PWR_BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP) + GPIO.setup(RST_BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP) + + GPIO.output(LED_STATUS_GPIO, GPIO.HIGH) + GPIO.add_event_detect(PWR_BUTTON_GPIO, GPIO.FALLING, callback=button_power_pressed_callback, bouncetime=DEBOUNCE_TIME) + GPIO.add_event_detect(RST_BUTTON_GPIO, GPIO.FALLING, callback=button_reboot_pressed_callback, bouncetime=DEBOUNCE_TIME) + + signal.signal(signal.SIGINT, signal_handler) + signal.pause() From 31b0e288e76c6f64bedebc5d8b16a524579cfe38 Mon Sep 17 00:00:00 2001 From: Fabio Nisci Date: Tue, 10 Nov 2020 18:00:05 +0100 Subject: [PATCH 2/2] readme with my added improvements --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 50f53cc..ffe30fc 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ Scripts used in our official [Raspberry Pi power button guide](https://howchoo.com/g/mwnlytk3zmm/how-to-add-a-power-button-to-your-raspberry-pi). +I added events handling for shutdown + reboot and a status LED. + ## Installation 1. [Connect to your Raspberry Pi via SSH](https://howchoo.com/g/mgi3mdnlnjq/how-to-log-in-to-a-raspberry-pi-via-ssh)