0

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/

1
  • You used global in the wrong place. It goes in the function where you want rotation to be considered a global, not local, name. Commented Mar 3, 2019 at 22:23

2 Answers 2

4

Simply declare it global within the function instead.

def countPulse(channel): 
  global rotation 
  rotation = rotation+1
  ...
Sign up to request clarification or add additional context in comments.

Comments

0

I figured it out. While the variable you intend to define retains a global scope, one needs to declare separately inside the function that it is of a global scope. The 'global' command can't be outside of the function.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.