Category Archives: code

detect.py

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import os
import sys
 
# Set pins to BOARD
GPIO.setmode(GPIO.BOARD)

# Setup pins for relay
Motor2A = 36
Motor2B = 32
Motor2E = 37
 
GPIO.setup(Motor2A,GPIO.OUT)
GPIO.setup(Motor2B,GPIO.OUT)
GPIO.setup(Motor2E,GPIO.OUT)
 
 
# Setup pins for filter
Motor1A = 16
Motor1B = 13
Motor1E = 7
 
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)
 
  
#PIR setup
#set up PIR pin
PIR_PIN = 15
#set PIR pin as input
GPIO.setup(PIR_PIN, GPIO.IN)

#set up BUTTON A pin
BUTTON_PINA = 31
GPIO.setup(BUTTON_PINA, GPIO.IN)

#set up BUTTON B pin
BUTTON_PINB = 33
GPIO.setup(BUTTON_PINB, GPIO.IN)

#below is the function MOTION which is called by the main program at the bottom
def MOTION(PIR_PIN):
				print "motion detected"
				# double check
#				time.sleep(2)
				while GPIO.input(PIR_PIN)==1:
					print "confirmed"
#					time.sleep(1)
					# switch relay on
					GPIO.output(Motor2A,GPIO.HIGH)
					GPIO.output(Motor2B,GPIO.LOW)
					GPIO.output(Motor2E,GPIO.HIGH)
					print "light on"
					# wait 20 seconds - can change this
					print "waiting"
					time.sleep(10)
					# check the PIR again, if its on wait for another 20 seconds
					while GPIO.input(PIR_PIN)==1:
						print "still waiting"
						time.sleep(5)
					#turn off the relay
					GPIO.output(Motor2E,GPIO.LOW)
					print "motion stopped"
					print "Light off" 
				
def BUTTONA(BUTTON_PINA):
				print "button A detected"
				time.sleep(1)
				while GPIO.input(BUTTON_PINA)==1:
					print "confirmed"
					os.system('sudo poweroff')

def BUTTONB(BUTTON_PINB):
				print "button B detected"
#				os.system("sudo ifup --force wlan0")


	
# ---MAIN PROGRAM STARTS------
# message is prined at startup & gives the PIR sensor 2 seconds to settle down before the program starts.
				
print "PIR Module test press Ctrl+C to exit"
#turn off the relay
GPIO.output(Motor2A,GPIO.HIGH)
GPIO.output(Motor2B,GPIO.LOW)
GPIO.output(Motor2E,GPIO.LOW)
print "Light off"

time.sleep(1) 
 
print "Sending signal"
GPIO.output(Motor1A,GPIO.LOW)
GPIO.output(Motor1B,GPIO.HIGH)
GPIO.output(Motor1E,GPIO.HIGH)
 
time.sleep(0.1)
 
GPIO.output(Motor1E,GPIO.LOW)

print "Filter off"

time.sleep(5)
print "ready"

# this runs all the time, checking to see if the PIR or buttons are triggered
try:
	GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION, bouncetime=300)
	GPIO.add_event_detect(BUTTON_PINA, GPIO.RISING, callback=BUTTONA, bouncetime=300)
	GPIO.add_event_detect(BUTTON_PINB, GPIO.RISING, callback=BUTTONB, bouncetime=300)
	while 1:
		time.sleep(100)
							  
# stop program if ctrl+C is pressed
except KeyboardInterrupt:
				print "quit"
				GPIO.cleanup()