Skip to content

Instantly share code, notes, and snippets.

@Pindar
Created July 7, 2018 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pindar/4b872f8d4fe375c64d7da7f2f5555ca5 to your computer and use it in GitHub Desktop.
Save Pindar/4b872f8d4fe375c64d7da7f2f5555ca5 to your computer and use it in GitHub Desktop.
pishutdown
#!/usr/bin/env python3
# shutdown/reboot(/power on) Raspberry Pi with pushbutton
import RPi.GPIO as GPIO
from subprocess import call
from datetime import datetime
import time
from signal import pause
# pushbutton connected to this GPIO pin, using pin 5 also has the benefit of
# waking / powering up Raspberry Pi when button is pressed
shutdownPin = 5
# if button pressed for at least this long then shut down. if less then reboot.
rebootMinSeconds = 3
# button debounce time in seconds
debounceSeconds = 0.01
GPIO.setmode(GPIO.BOARD)
GPIO.setup(shutdownPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
buttonPressedTime = None
def buttonStateChanged(pin):
global buttonPressedTime
if not (GPIO.input(pin)):
# button is down
if buttonPressedTime is None:
buttonPressedTime = datetime.now()
else:
# button is up
if buttonPressedTime is not None:
elapsed = (datetime.now() - buttonPressedTime).total_seconds()
buttonPressedTime = None
if elapsed >= debounceSeconds:
# button pressed for more than specified time, shutdown
call(['shutdown', '-h', 'now'], shell=False)
elif elapsed >= rebootMinSeconds:
# button pressed for a shorter time, reboot
call(['shutdown', '-r', 'now'], shell=False)
# subscribe to button presses
GPIO.add_event_detect(shutdownPin, GPIO.BOTH, callback=buttonStateChanged)
pause()
[Service]
ExecStart=/usr/local/bin/pishutdown.py
WorkingDirectory=/usr/local/bin/
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=pishutdown
User=root
Group=root
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment