所以我开始使用hc-sr04超声波传感器并遇到了问题。我想读取多个传感器(两个用于启动器),但我在两个传感器上获得相同的距离值。这是代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Adafruit_BBIO.GPIO as GPIO
import time
def distanceMeasurement(TRIG,ECHO):
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulseStart = time.time()
while GPIO.input(ECHO) == 1:
pulseEnd = time.time()
pulseDuration = pulseEnd - pulseStart
distance = pulseDuration * 17150
distance = round(distance, 2)
return distance
#Configuration
GPIO.setup("P9_15",GPIO.OUT) #Trigger
GPIO.setup("P9_12",GPIO.IN) #Echo
GPIO.setup("P9_11",GPIO.OUT)
GPIO.setup("P9_13",GPIO.IN)
#Security
GPIO.output("P9_11", False)
GPIO.output("P9_15", False)
time.sleep(0.5)
#main Loop
try:
while True:
for i in range(2):
if i == 0:
recoveredDistance = distanceMeasurement("P9_11","P9_13")
print "Distance1: ",recoveredDistance,"cm"
elif i == 1:
recoveredDIstance = distanceMeasurement("P9_15","P9_12")
print "Distance2: ",recoveredDistance,"cm"
time.sleep(1)
except KeyboardInterrupt:
print "Measurement stopped by user"
GPIO.cleanup()
无论距离传感器2上的物体的距离如何,我都得到相同的读数,传感器1中读取的距离是显示的;似乎忽略了sensor2。
做一些“手动调试”(即打印TRIG,ECHO)我注意到该函数重现了正确的参数,这里是“调试”的输出:
P9_11
P9_13
Distance1: 20.79 cm
P9_15
P9_12
Distance2: 20.79 cm
P9_11
P9_13
Distance1: 20.13 cm
P9_15
P9_12
我想用一个功能来读取所有传感器。提前谢谢
答案 0 :(得分:1)
您打印两次相同的结果,因为第二次测量保存为recoveredDIstance
。所以recoveredDistance
没有变化。 Python区分大小写。
while True:
recoveredDistance = distanceMeasurement("P9_11","P9_13")
print "Distance1: ", recoveredDistance, "cm"
recoveredDistance = distanceMeasurement("P9_15","P9_12")
print "Distance2: ", recoveredDistance, "cm"
time.sleep(1)