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

时间:2019-03-03 22:05:32

标签: python python-3.x raspberry-pi global-variables gpio

我删除了以下代码。它是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/

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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