0

I defined callback functions for each GPIO explicitly and it was working fine. However, this was a bit much boilerplate code for me. Therefore, I just had the idea to realize this initialization in a for-loop:

# Configure Switches:
T = [4,17,18,27,22,23,24,25,5,6]
for i in range(0,10):
    GPIO.setup(T[i], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.add_event_detect(T[i], GPIO.BOTH, callback=lambda x: OnButtonPress(i+1), bouncetime=300)

For all buttons that I press the callback function OnButtonPress is called, however always with the button ID 10, independent from which button I press. It seams that the lambda is always called with 10 as parameter. What am I doing wrong here?

Matthias
  • 135
  • 10
  • Does this answer your question? [How do I create a list of Python lambdas (in a list comprehension/for loop)?](https://stackoverflow.com/questions/452610/how-do-i-create-a-list-of-python-lambdas-in-a-list-comprehension-for-loop) – jasonharper Oct 14 '20 at 17:54
  • when i do the following: ```python T = [4,17,18,27,22,23,24,25,5,6] for i in range(0,10): GPIO.setup(T[i], GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(T[i], GPIO.BOTH, callback=lambda x=i: OnButtonPress(x), bouncetime=300) ``` and I press the button 4 or 17 the callback function is also called with 4 and 17 but it should be called with 1 and 2!! How is that posisble?????? – Matthias Oct 14 '20 at 18:13
  • Your callback is being called with a parameter, which is evidently the pin number; this overwrites the value of `x` that you provided. You need to declare a dummy parameter first, to receive that, followed by the `x=i` to capture your desired value. – jasonharper Oct 14 '20 at 18:21
  • i don't get it, how is the ```i``` becoming suddenly the value of ```T[I]``` that makes no sense to me? – Matthias Oct 14 '20 at 22:55
  • 1
    The callback was called *with a parameter* - it replaced the default value you had assigned to `x`. That parameter had the same value as `T[i]`. Write it as `lambda _, x=i: ...` so that this parameter gets ignored, and your value of `i` gets preserved. – jasonharper Oct 15 '20 at 00:19

0 Answers0