我截取了以下代码。它是物联网液体流量计演示的一部分(因此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/
我想出来了。虽然要定义的变量保留全局范围,但需要在函数内部单独声明它属于全局范围。“global”命令不能在函数之外。在
只需在函数中声明它是全局的。在
相关问题 更多 >
编程相关推荐