Search code examples
pythonbuttonwhile-looparduinofirmata

while not error-how to make an alternative


This is the current code:

def wait_for_button(button):
    while not (button.read()) :
        pass
wait_for_button(push_button1)
print('Hi')
wait_for_button(push_button2)
print('Bye')

But the problem with this code is that push_button1 has to be pressed first, and, only then, will the push button 2 work. If push button 1 is not pressed before push button 2, it will not print out 'Bye' (referring to the code above).

Is there a way such that instead of going in a sequence (pushputton1->pushbutton2) ,it can go either way, i.e. no matter which button is pressed first, the code will still work? Thanks


Solution

  • If I understand correctly the question, you want to exit when button 2 is pressed (regardless whether button 1 has been pressed). You could create the following function for such a case:

    def wait_for_buttons(button1, button2):
        button1_pressed = False
        button2_pressed = False
    
        while not button2_pressed:
            if button1.read():
                button1_pressed = True
                print("Hi")
            if button2.read():
                button2_pressed = True
    
    wait_for_buttons(push_button1, push_button2)
    print('Bye')