【问题标题】:Python UnboundLocalError using threadsPython UnboundLocalError 使用线程
【发布时间】: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


    【解决方案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
    

    【讨论】:

    • 我发现电路有问题,谢谢,你说的我会记住的,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    相关资源
    最近更新 更多