I've given this a code a good go and got it working to a point. The first section of the code is for the distance sensor and seems to work fine, also the 'if' statement, when I get it to check the distance between 2cm and 30cm also seems to work fine by switching on a relay for 5 seconds, but what I would now like to do is have it switch on 2 relays for 5 seconds, not just the 1, but not sure how to add the second relay into the mix. Currently I have the Pi connected to a 4 relay board.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
print "Distance measurement in progress"
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while True:
GPIO.output(TRIG, False)
print "Waitng For Sensor To Settle"
time.sleep(2)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
if distance > 2 and distance < 400:
print "Distance:",distance - 0.5,"cm"
else:
print "Out Of Range"
GPIO.setwarnings(False)
if distance >2 and < 30:
pinList = [3]
for i in pinList:
GPIO.setup(i, GPIO.OUT)
try:
GPIO.output(3, GPIO.LOW)
print "ON"
time.sleep(5)
GPIO.output(3, GPIO.HIGH)
print "OFF"
except KeyboardInterrupt:
print " Quit"
GPIO.cleanup()
if distance >2 and < 30:is not valid syntax, if you want to chain the expression it isif 2 < distance < 30: