全局变量声明+未绑定错误:赋值前引用局部变量?

2024-09-28 22:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我截取了以下代码。它是物联网液体流量计演示的一部分(因此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()

错误:

^{pr2}$

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

PS:这里解释了回调和通道变量:https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/


Tags: importgpiotimesyssensorflowtotaldecimal
2条回答

我想出来了。虽然要定义的变量保留全局范围,但需要在函数内部单独声明它属于全局范围。“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()

只需在函数中声明它是全局的。在

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

相关问题 更多 >