7

I want to set a callback function to run when an event occurs in a GPIO. I'm designing a class and I want to have the callback method inside it too. Here's an excerpt of the code:

import RPi.GPIO as gpio

class WheelEncoder:
  'Encapsulates the attributes and methods to use a wheel encoder sensor'

  inputPin = 0
  ticks = 0

  def __init__(self, inputPin):
    self.inputPin = inputPin

    gpio.setmode(gpio.BOARD)
    gpio.setup(self.inputPin, gpio.IN, pull_up_down=gpio.PUD_UP)
    gpio.add_event_detect(self.inputPin, gpio.RISING, event_callback)

  def getTicks(self):
    return self.ticks

  def resetTicks(self):
    self.ticks = 0

  def event_callback(channel):
    self.ticks += 1

And here is the output of calling it (from another file):

Traceback (most recent call last):
  File "test-WheelEncoder.py", line 5, in <module>
    sensor = WheelEncoder(3, 10, 3)
  File "/home/pi/codes/sensors/WheelEncoder.py", line 20, in __init__
    gpio.add_event_detect(self.inputPin, gpio.RISING, event_callback)
NameError: global name 'event_callback' is not defined

Im not sure what it could be.

0

1 Answer 1

7

Just found the answer. I changed the call to add_event_detect to be

gpio.add_event_detect(self.inputPin, gpio.RISING, self.event_callback)

and changed the signature of event_callback to be

event_callback(self, channel):

The complete code can be seen in my own repository: https://github.com/luizfzs/python-pi-sensor-modules/blob/master/WheelEncoder.py#L28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.