0

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?

3
  • What sort of parameters do you want to pass to your callback? It would help if you could update your question to show us exactly what you're trying to do (i.e., show us the code of your desired callback function and how you're trying to call it). There may be multiple ways of accomplishing similar goals, and having the additional context means we'll give you appropriate advice. Commented Mar 11, 2022 at 17:09
  • I've updated my question. Please check. Thanks! Commented Mar 11, 2022 at 17:57
  • I would suggest you to modify your DTS to add gpio-keys driver and get a proper IRQ handler for that. Commented Mar 14, 2022 at 13:38

1 Answer 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)) 
Sign up to request clarification or add additional context in comments.

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.