2015-07-05 42 views
0

我試圖在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" 

回答

1

你應該總是嘗試&減少一個例子到最小工作。然後,它變得很清楚發生了什麼:

while True 
    if False: # not reached 
     pulse_start = time.time() 
    else: 
     pulse_end = time.time() 
    print pulse_end - pulse_start # undbound local error! 

這有什麼好做的線程本身,而是可能與GPIO的狀態是不同的,由於傳感器的串擾,因此在使用前你沒有定義puse_start。通常的解決方法是預先設置一個值 - 無論是有用的還是哨兵值,例如None

pulse_start = None 
pulse_end = None  
while True: 
    if <condition>: 
     pulse_start = time.time() 
    else: 
     pulse_end = time.time() 
    if pulse_start is not None and pulse_end is not None: 
     print "length", pulse_end - pulse_start 
     pulse_end = None # reset pulse_end to prevent printing out a negative length if you started with the second execution path 
+0

我在電路中發現了一個問題,謝謝,我會記住你說的,謝謝很多。 –