0

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

David Duran
  • 1,786
  • 1
  • 25
  • 36
strilz
  • 63
  • 7

2 Answers2

1

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')
David Duran
  • 1,786
  • 1
  • 25
  • 36
  • yea sort of, my idea is that there shouldn't be a fixed path that the code needs to follow(in my case, if button 1 is not pressed, button 2 wouldn't work). – strilz Aug 05 '20 at 14:04
  • Ok, so the code I provided should work when button 2 is pressed regardless whether button 1 is pressed or not. Has it solved your problem? – David Duran Aug 05 '20 at 14:06
0

If I understand correctly and you want to check if both buttons are pressed and only then print 'Bye'. You can create a 2 boolean variables for button 1 and 2, then if both variables are set to true, print. Something like this:

def wait_for_button(button1,button2):
    button_pressed1=False
    button_pressed2=False

    print ("Hi")
    while not button_pressed1 and not button_pressed2:
        if button1.read():
            button_pressed1=True
        if button2.read():
            button_pressed2=True
    print ("Bye")

This way it doesn't matter which button is pressed first, once both has been pressed in any order, the while loop ends and the function prints "Bye".

Dharman
  • 30,962
  • 25
  • 85
  • 135