Last active
March 27, 2017 14:46
-
-
Save GitRay/e7404cb817d60eee2e177ecffbdd0a60 to your computer and use it in GitHub Desktop.
Reset/Shutdown switch for Raspberry Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
# This script is meant to be used to monitor a button on the | |
# Raspberry Pi. I connected the button between pins 13 and 14, | |
# chosen because BCM 27 is not used for anything else and it is | |
# right next to a ground, so I can use a single connector. | |
# | |
# If the button is pressed breifly (less than 5 seconds), the Pi | |
# will reboot. If the button is held down longer, it will shut down (halt). | |
# After a halt, you will need to cycle power to restart. | |
# | |
# I needed this to use with Emulation Station / RetroPie, since some emulators can get | |
# "stuck" and I don't have a keyboard attached to the Pi. Restarting the | |
# Pi by power cycling is generally a bad idea due to data corruption on | |
# the SD card. | |
# | |
# I wrote this because other solutions on the web use a hard loop to poll the GPIO | |
# status, which seems like a waste of resources. Here I instead use interrupts, so this | |
# script just sleeps most of the time until woken up with the button press. I also did | |
# not see the button-driven shutdown function anywhere else. | |
# | |
# To use, add this line to /etc/rc.local | |
# python /home/pi/restart_shutdown_watcher.py --silent & | |
# | |
# Assuming, of course, that you put the script in the pi home directory :) | |
from __future__ import print_function | |
import RPi.GPIO as GPIO | |
import time, os | |
GPIO.setmode(GPIO.BCM) | |
# GPIO 27 set up as inputs, pulled up to avoid false detection. | |
# Port is wired to connect to GND on button press, | |
# so we'll be setting up falling edge detection. | |
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
try: | |
# first wait for the button press | |
GPIO.wait_for_edge(27, GPIO.FALLING, bouncetime=300) | |
press_time = time.time() | |
# now wait for the rise (button let go) | |
GPIO.wait_for_edge(27,GPIO.RISING,bouncetime=100,timeout=5001) | |
if time.time() - press_time > 5.0: | |
print("Shutdown") | |
os.system("sudo shutdown -h now") | |
else: | |
print("Reboot") | |
os.system("sudo shutdown -r now") | |
except KeyboardInterrupt: | |
pass | |
GPIO.cleanup() # clean up GPIO on normal exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment