OhioJoe

RPi_shutdown.py

Aug 14th, 2017
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. #!/usr/bin/python
  2. # shutdown/reboot(/power on) Raspberry Pi with pushbutton
  3.  
  4. import RPi.GPIO as GPIO
  5. from subprocess import call
  6. from datetime import datetime
  7. import time
  8. import os
  9.  
  10. # pushbutton connected to this GPIO pin, using pin 5 also has the benefit of
  11. # waking / powering up Raspberry Pi when button is pressed
  12. shutdownPin = 37
  13.  
  14. # if button pressed for at least this long then shut down. if less then reboot.
  15. shutdownMinSeconds = 6
  16.  
  17. # button debounce time in seconds
  18. debounceSeconds = 0.01
  19.  
  20. GPIO.setmode(GPIO.BOARD)
  21. GPIO.setup(shutdownPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  22.  
  23. buttonPressedTime = None
  24.  
  25.  
  26. def buttonStateChanged(pin):
  27.     global buttonPressedTime
  28.  
  29.  
  30.     if not (GPIO.input(pin)):
  31.         # button is down
  32.         if buttonPressedTime is None:
  33.             buttonPressedTime = datetime.now()
  34.     else:
  35.         # button is up
  36.         if buttonPressedTime is not None:
  37.             elapsed = (datetime.now() - buttonPressedTime).total_seconds()
  38.             buttonPressedTime = None
  39.             if elapsed >= shutdownMinSeconds:
  40.                 # button pressed for more than specified time, shutdown
  41.                 call(['shutdown', '-h', 'now'], shell=False)
  42.             elif elapsed <= 4:
  43.                 Call(['shutdown','r', 'now'], shell=False)
  44.             elif elapsed >= debounceSeconds:
  45.                     # button pressed for a shorter time, reboot
  46.                 os.system("python /home/pi/oled/NanoPi-NEO_OLED_MPD/./b.py")
  47.        
  48.  
  49. # subscribe to button presses
  50. GPIO.add_event_detect(shutdownPin, GPIO.BOTH, callback=buttonStateChanged)
  51.  
  52. while True:
  53.     # sleep to reduce unnecessary CPU usage
  54.     time.sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment