我已经给了这个代码一个很好的去,让它工作到一定程度。代码的第一部分用于距离传感器并且看起来工作正常,也就是'if'语句,当我检查2cm和30cm之间的距离时,通过接通继电器5秒也似乎工作正常,但我现在要做的是让它接通2个继电器5秒,而不仅仅是1,但不确定如何将第二个继电器添加到混音中。目前我将Pi连接到4继电器板。
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()
答案 0 :(得分:1)
看起来你已经将许多不同来源切割在一起。其中一个原始脚本只是使用一个列表(pinList
)来迭代 - 这个原始用法似乎已经丢失了。
以下代码可让您重回正轨。可能值得比较一下我所做的改变和进一步阅读。您需要更改第11行以匹配附加继电器的引脚号。
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
# Add your relay output pins here:
pinList = [3, your_other_relaypin]
for pin in pinList:
GPIO.setup(pin, GPIO.OUT)
print "Distance measurement in progress"
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
try:
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}cm".format(distance=(distance - 0.5) )
else:
print "Out Of Range"
if distance >2 and distance < 30:
for pin in pinList:
print "ON PIN {pin}".format(pin=pin)
GPIO.output(pin, GPIO.LOW)
time.sleep(5)
for pin in pinList:
print "OFF PIN {pin}".format(pin=pin)
GPIO.output(pin, GPIO.HIGH)
except KeyboardInterrupt:
print " Quit"
GPIO.cleanup()