【发布时间】:2015-09-22 15:02:29
【问题描述】:
我正在尝试在 Raspberry Pi2 上使用接近传感器,并且我希望每个传感器在不同的线程上运行,因此我使用了线程模块。如果我只使用 2 个线程,一切正常,但是当我尝试运行 3 个线程时,我收到此错误:
线程 Thread-3 中的异常: 回溯(最近一次通话最后): 文件“/usr/lib/python2.7/threading.py”,第 552 行,在 __bootstrap_inner 自我运行() 运行中的文件“/usr/lib/python2.7/threading.py”,第 505 行 self.__target(*self.__args, **self.__kwargs) 文件“range_sensor.py”,第 52 行,测量中 脉冲持续时间 = 脉冲结束 - 脉冲开始 UnboundLocalError:赋值前引用了局部变量“pulse_start”
这是代码,我不明白哪里错了
tuples = [(1, 'Bagno Cla', 'Toilet paper', 23, 24),
(1, 'Bagno Ladispe', 'Trash', 25, 8),
(2,'Bagno inventato', 'Soap', 16,20)]
def measure(bathroomFloor, bathroomId, item, TRIG, ECHO):
# getting raspberry and sensors ready
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
print "Waiting For Sensor To Settle"
time.sleep(2)
T=60
while True:
print "Distance Measurement In Progress"
time.sleep(5) #sampling period
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)
print "Measured distance in "+bathroomId+":",distance,"cm"
print "Time of measure in "+bathroomId+":",time.strftime("%H:%M")
GPIO.cleanup()
return
# this is the part of code that launches each thread
try: #launching threads
i = 0
while i < len(tuples):
t = threading.Thread(target=measure, args=tuples[i])
t.start();
i+=1
except:
print "Error: unable to start thread"
【问题讨论】:
标签: python multithreading raspberry-pi