I'm learning python and gpio using the examples here: https://gpiozero.readthedocs.io/en/stable/recipes.html
I wanted to extend the code to more than one button and pass a parameter to a function (for example the button number). The code works for both buttons when I don't pass a parameter, but doesn't when I pass one. I'm sure it's related to the note here, but I don't know how to get around that. Here's the code that doesn't work, in fact it prints Hello! 1 then Hello! 2 without any buttons being pressed then does nothing when either button is pressed, but prints Goodbye! when either button is released. How do I fix the code to call the function with a parameter when either button is pressed? Thank you.
from gpiozero import Button
from signal import pause
def say_hello(button_number):
print("Hello!", button_number)
def say_goodbye():
print("Goodbye!")
button1 = Button(2)
button2 = Button(3)
button1.when_pressed = say_hello(1)
button1.when_released = say_goodbye
button2.when_pressed = say_hello(2)
button2.when_released = say_goodbye
pause()
Code that works based on the answer below:
from gpiozero import Button
from signal import pause
def say_hello(button_number):
if button_number == 1:
return lambda: print("Hello, Button 1!")
if button_number == 2:
return lambda: print("Hello, Button 2!")
def say_goodbye():
print("Goodbye!")
button1 = Button(2)
button2 = Button(3)
button1.when_pressed = say_hello(1)
button1.when_released = say_goodbye
button2.when_pressed = say_hello(2)
button2.when_released = say_goodbye
pause()