我試圖在Raspberry Pi2上使用接近傳感器,我希望每個傳感器都在不同的線程上運行,所以我使用了線程模塊。如果我只用2個線程,一切工作正常,但是當我嘗試運行3個線程,我得到這個錯誤:使用線程的Python UnboundLocalError
Exception in thread Thread-3: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 505, in run self.__target(*self.__args, **self.__kwargs) File "range_sensor.py", line 52, in measure pulse_duration = pulse_end - pulse_start UnboundLocalError: local variable 'pulse_start' referenced before assignment
下面是代碼,我不明白什麼是錯
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"
我在電路中發現了一個問題,謝謝,我會記住你說的,謝謝很多。 –