Search code examples
pythonpython-3.xraspberry-piglobal-variablesgpio

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


I have the following code snipped. It is part of a demo for an IoT liquid flow meter (hence the GPIO references). When running it the function seems to ignore that the variable rotation has been defined as a global variale

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

Error:

Unbound Error: local variable 'rotation' referenced before assignment

How do I declare the variable in a global way without resetting it to zero at every invocation of countPulse?

PS: The callback and channel variable are explained here: https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/


Solution

  • Simply declare it global within the function instead.

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