# python program to detect if switch has been thrown. # basic idea is to tell if a un-used light switch in the house has been # moved from on to off or back. If it has been moved, trigger the webserver # scripts to turn the relays on (or off as needed) and hence the lights #uses GPIO pin 2 as an input which is controlled by the switch #import the library that allows us to access the GPIO pins #alias it to GPIO to make things simpler import RPi.GPIO as GPIO #import the library that allows us to use time functions import time #import the libs to send web data to the far side import urllib import urllib2 # # This routine is called when a state has changed. and it is passed the new state # If the new state is "0", the switch has been turned on, so turn on lights # if not, then the switch must have been turned off, so turn off lights def shed_lights(value): name = "button name" if value == 0: #switch has been moved to "On" position, turn on lights data = {"DoorON" : name } encoded_data = urllib.urlencode(data) content = urllib2.urlopen("http://192.168.0.102/index.php?action=send",encoded_data) else: # if they switch was not turned on, it must have been turned Off data = {"DoorOFF" : name } encoded_data = urllib.urlencode(data) content = urllib2.urlopen("http://192.168.0.102/index.php?action=send",encoded_data) # end of subroutine "shed_lights" # Start of main code, a simple one pass program with a endless while loop #Use the BCM pin numbering scheme GPIO.setmode(GPIO.BCM) #Turn off warnings on multiple programs playing with the pins.. GPIO.setwarnings(False) #set gpio pin 2 to be used as an input GPIO.setup(2, GPIO.IN) # read the state of the switch at the start of the world. # A state of 1 means the switch is in the down or off position # A state of 0 means the switch is Up # We want to track changes in position. If the switch has been moved from off to on # We should trigger the "on" scripts for the shed lights. # # If the switch has been moved from on to off, we should turn the shed lights off a = 0 x = GPIO.input(2) a = x while 1==1: x = GPIO.input(2) # check to see if state has changed if x != a: #the state has changed... time to do something! shed_lights(x) a = x time.sleep(1)