# 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 # assumes you are on the machine controlling the relays, as apposed to switch.py which # sends data to the web server on a remote machine. #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 #add socket library import socket #Use the BCM pin numbering scheme GPIO.setmode(GPIO.BCM) # # 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): if value == 0: #switch has been moved to "On" position, turn on lights # first turn on shed lights (23) then motion lights (24) GPIO.output(23, GPIO.HIGH) GPIO.output(24, GPIO.HIGH) # send a message to the "ON" listening port on 1Pi s = socket.socket() # Create a socket object port = 1237 # Reserve a port for your service. s.connect(('192.168.0.101', port)) s.close() else: # if they switch was not turned on, it must have been turned Off GPIO.output(23, GPIO.LOW) GPIO.output(24, GPIO.LOW) # send a message to the "Off" listening port on 1Pi s = socket.socket() # Create a socket object port = 1247 # Reserve a port for your service. s.connect(('192.168.0.101', port)) s.close() # 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) # gpio pins 23 and 24 control the shed light relays GPIO.setup(23, GPIO.OUT) GPIO.setup(24, GPIO.OUT) # 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)