Skip to content

Instantly share code, notes, and snippets.

@MicahStevens
Last active July 14, 2017 19:47
Show Gist options
  • Save MicahStevens/090fb4f6f9991f2131fddb28d4c7c5dd to your computer and use it in GitHub Desktop.
Save MicahStevens/090fb4f6f9991f2131fddb28d4c7c5dd to your computer and use it in GitHub Desktop.
One way to issue a system command when someone pushes a button connected to the gpio
"""
Some references:
https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/
https://stackoverflow.com/questions/89228/calling-an-external-command-in-python
"""
import RPi.GPIO as GPIO
import signal
import time
import sys
from subprocess import call
# first look for sigint so we can release the buttons if the script exits.
def signal_handler(signal, frame):
GPIO.cleanup()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler) # keep an eye our for SIGINT (ctrl-c)
# setup gpio (according to hersh's orignal script)
def keyPressed(key):
if key == 11:
# do 11 stuff like halt the pi
call(["sudo", "halt"])
if key == 13:
# do 13 stuff
# etc etc
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)
GPIO.add_event_detect(11, GPIO.RISING, callback=keyPressed)
GPIO.setup(13, GPIO.IN)
GPIO.add_event_detect(13, GPIO.RISING, callback=keyPressed)
GPIO.setup(15, GPIO.IN)
GPIO.add_event_detect(15, GPIO.RISING, callback=keyPressed)
GPIO.setup(16, GPIO.IN)
GPIO.add_event_detect(16, GPIO.RISING, callback=keyPressed)
GPIO.setup(7, GPIO.IN)
GPIO.add_event_detect(17, GPIO.RISING, callback=keyPressed)
while True:
time.sleep(1) # sleep for a second while the system does other stuff.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment