Skip to content

Instantly share code, notes, and snippets.

@danielepantaleone
Created May 6, 2019 09:27
Show Gist options
  • Save danielepantaleone/4b62c192d61d66f725b38ae3f30bb896 to your computer and use it in GitHub Desktop.
Save danielepantaleone/4b62c192d61d66f725b38ae3f30bb896 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import subprocess
BUTTON_PIN = 40
BUTTON_SHUTDOWN_TIMEOUT = 3
# we will use the pin numbering to match the pins on the Pi, instead of the
# GPIO pin outs (makes it easier to keep track of things)
GPIO.setmode(GPIO.BOARD)
# use the same pin that is used for the reset button (one button to rule them all!)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
buttonPressed = False
buttonPressedTime = 0
while True:
if GPIO.input(BUTTON_PIN) == GPIO.HIGH:
# button was pushed
if not buttonPressed:
# button wasn't pushed before so track state change
buttonPressed = True
buttonPressedTime = time.time()
else:
# button was pressed, check if it's time to shutdown
if time.time() - buttonPressedTime >= BUTTON_SHUTDOWN_TIMEOUT:
subprocess.call("shutdown -h now", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
buttonPressed = False
buttonPressedTime = 0
time.sleep(.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment