Home > Enterprise >  Can you bind two functions to button.when_pressed in python gpiozero?
Can you bind two functions to button.when_pressed in python gpiozero?

Time:12-19

I am trying to bind two functions to a button, so for example I want to toggle a buzzer and LED with a single button. Is there a way to attach two functions to the same button or can a button only do a single thing at once?

For example:

button.when_pressed = led.toggle && buzzer.toggle

CodePudding user response:

Bind to a function that calls both functions:

def toggle_led_and_buzzer():
    led.toggle()
    buzzer.toggle()

button.when_pressed = toggle_led_and_buzzer

CodePudding user response:

You can use 2 solutions. Just merge the two functions into a single function, then call up that single function with the button, or alternatively using a lambda

SOLUTION N.1

def ledtoggle_buzzertoggle():
    led.toggle()
    buzzer.toggle()

button.when_pressed = ledtoggle_buzzertoggle

SOLUTION N.2

You can also use lambda

button.when_pressed = lambda:[led.toggle(), buzzer.toggle()] #or without square brackets
  • Related