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

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

我截取了以下代码。它是 IoT 液体流量计演示的一部分(因此引用了 GPIO)。当 运行 时,该函数似乎忽略了变量 rotation 已被定义为全局变量

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
  ...

我明白了。虽然您打算定义的变量保留全局范围,但需要在函数内部单独声明它是全局范围的。 'global'命令不能在函数外。

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()