'How to pass args to the callback function in RPi.GPIO.add_event_detect()
I've tried help(RPi.GPIO.add_event_detect) and checked its official wiki with no answer to that. The official example is like:GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback, bouncetime=200)
Is there any way to pass args to my callback function (other than the pin channel) ?
Updates:
What I'm trying to do is to stop/resume a camera&servo task via a button. My code is like:
active = [False]
GPIO.add_event_detect(channel, GPIO.BOTH, callback=button_callback)
while True:
if active[0]:
# camera&servo doing something which lasts seconds per loop
I want to pass the arg active to function button_callback in order to set it True/False. If I directly put GPIO.input(channel) in the while loop, I might miss the button input.
So how to pass that arg to the callback or is there any better way to achieve that?
Solution 1:[1]
You don't need to pass active to your callback function. The easiest solution for what you're doing is probably making active a global variable, so that your callback looks like this:
active = False
def button_callback(channel):
global active
active = GPIO.input(channel)
GPIO.add_event_detect(channel, GPIO.BOTH, callback=button_callback)
while True:
if active:
# camera&servo doing something which lasts seconds per loop
You're probably going to have to deal with debouncing your switch.
If you really want to pursue your original plan and pass the active list to your callback function, something like this should work:
def button_callback(channel, active):
active[0] = GPIO.input(channel)
GPIO.add_event_detect(channel, GPIO.BOTH,
callback=lambda channel: button_callback(channel, active))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | larsks |
