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)
Raspberry Pi Stack Exchange is a question and answer site for users and developers of hardware and software for Raspberry Pi. It only takes a minute to sign up.Sign up to join this community
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.
user_gpio:= 0-31. edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE. func:= user supplied callback function.
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.