http://pastebin.com/sawEjzPr
[code python]
import RPi.GPIO as GPIO
import time
import threading
GPIO.setmode(GPIO.BCM)
TRIG = 14
ECHO = 15
L = 24
TRIG_W = 23
ECHO_W = 18
distance1 = 0
distance2 = 0
a = 0
b = 0
c = 0
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.setup(TRIG_W,GPIO.OUT)
GPIO.setup(ECHO_W,GPIO.IN)
GPIO.setup(L,GPIO.OUT)
def ultrasonic1():
try:
GPIO.output(TRIG, False)
time.sleep(1)
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
global distance1
distance1 = pulse_duration * 17150
distance1 = round(distance1, 2)
print "Distance1:",distance1,"cm"
if distance1 < 20:
global a
a += 1
time.sleep(0.2)
except KeyboardInterrupt:
print "KeyboardInterrupt detected!"
GPIO.cleanup()
def ultrasonic2():
try:
GPIO.output(TRIG_W, False)
time.sleep(1)
GPIO.output(TRIG_W, True)
time.sleep(0.00001)
GPIO.output(TRIG_W, False)
while GPIO.input(ECHO_W)==0:
pulse_start = time.time()
while GPIO.input(ECHO_W)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
global distance2
distance2 = pulse_duration * 17150
distance2 = round(distance2, 2)
print "Distance2:",distance2,"cm"
if distance2 < 20:
global b
b += 1
time.sleep(0.2)
except KeyboardInterrupt:
print "KeyboardInterrupt detected!"
GPIO.cleanup()
try:
while True:
e1 = threading.Event()
e2 = threading.Event()
t1 = threading.Thread(target=ultrasonic1)
t2 = threading.Thread(target=ultrasonic2)
t1.start()
t2.start()
if b > a:
c = 1
elif a > b:
c = 0
if c <= 0:
print "a = ", a, "b = ", b
print "c = ", c
print "turn off"
GPIO.output(L,GPIO.LOW)
elif c >= 1:
print "a = ", a, "b = ", b
print "c = ", c
print "turn on"
GPIO.output(L,GPIO.HIGH)
time.sleep(0.5)
except KeyboardInterrupt:
print "KeyboardInterrupt detected!"
t1.join()
t2.join()
GPIO.cleanup()[/code]