繁体   English   中英

全局变量声明+未绑定错误:分配前已引用局部变量?

[英]Global variable declaration + Unbound Error: local variable referenced before assignment?

我有下面的代码片段。 它是IoT液体流量计演示的一部分(因此GPIO参考)。 运行它时,该函数似乎忽略了变量旋转已定义为全局变量

import RPi.GPIO as GPIO
import time, sys

LIQUID_FLOW_SENSOR = 32

GPIO.setmode(GPIO.BOARD)
GPIO.setup(LIQUID_FLOW_SENSOR, GPIO.IN, pull_up_down = GPIO.PUD_UP)

global rotation
rotation = 0

def countPulse(channel):
   rotation = rotation+1
   print ("Total rotation = "+str(rotation))
   litre = rotation / (60 * 7.5)
   two_decimal = round(litre,3)
   print("Total consumed = "+str(two_decimal)+" Litres")

GPIO.add_event_detect(LIQUID_FLOW_SENSOR, GPIO.FALLING, callback=countPulse)

while True:
    try:
        time.sleep(1)

    except KeyboardInterrupt:
        print 'Program terminated, Keyboard interrupt'
        GPIO.cleanup()
        sys.exit()

错误:

Unbound Error: local variable 'rotation' referenced before assignment

如何以全局方式声明变量,而不在每次调用countPulse时将其重置为零?

PS:回调和通道变量在这里进行了说明: https : //sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/

只需在函数内全局声明即可。

def countPulse(channel): 
  global rotation 
  rotation = rotation+1
  ...

我想到了。 尽管您打算定义的变量保留了全局范围,但需要在函数内部分别声明它具有全局范围。 “全局”命令不能在函数之外。

import RPi.GPIO as GPIO
import time, sys

LIQUID_FLOW_SENSOR = 32

GPIO.setmode(GPIO.BOARD)
GPIO.setup(LIQUID_FLOW_SENSOR, GPIO.IN, pull_up_down = GPIO.PUD_UP)

rotation = 0

def countPulse(channel):
   global rotation
   rotation = rotation+1
   print ("Total rotation = "+str(rotation))
   litre = rotation / (60 * 7.5)
   two_decimal = round(litre,3)
   print("Total consumed = "+str(two_decimal)+" Litres")

GPIO.add_event_detect(LIQUID_FLOW_SENSOR, GPIO.FALLING, callback=countPulse)

while True:
    try:
        time.sleep(1)

    except KeyboardInterrupt:
        print 'Program terminated, Keyboard interrupt'
        GPIO.cleanup()
        sys.exit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM