2

Is there any way to pass args to the callback function when using

GPIO.add_event_detect(17, GPIO.FALLING, callback=my_callback, bouncetime=300)
  • 1
    I don't use the Python libraries for programming my Pis, but in the other languages I do use, no, you cannot. You should however be able to set up some global variables and access them from within your ISR though... – stevieb Jul 21 '17 at 12:48
1

I am not sure about RPi.GPIO but Joan's pigpio library also offers callbacks so I will try to explain how this could be achieved with pigpio as an example assuming the technique can be transferred to RPi.gpio (after all it's just Python doing the trick).

functools.partial(func, *args, **keywords) can solve this task: Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.

Syntax of pigpio's callback(user_gpio, edge, func):

Calls a user supplied function (a callback) whenever the specified GPIO edge is detected.

Parameters

user_gpio:= 0-31.
     edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
     func:= user supplied callback function.

Example

import pigpio
pi = pigpio.pi()

def cbf(gpio, level, tick):
    print(gpio, level, tick)

cb1 = pi.callback(22, pigpio.EITHER_EDGE, cbf)

Using functool.partial() to reduce the argument list:

from functools import partial

def cbf_with_argument(gpio, level, tick, myarg):
    print(gpio, level, tick, myarg)

cb1 = pi.callback(22, 
                  pigpio.EITHER_EDGE, 
                  partial(cbf_with_argument, myarg=4))

This sets up the callback with myarg set to 4. partial also handles *args, **kwargs argument lists in a similar fashion the example above uses just one argument for simplicity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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