1

I am using python to control an arduino.I want the python code to wait for the button to be pressed, and then move onto the next line.In the current code I have, the code sleeps for x seconds and checks if button has been pushed,if button is not pushed, it skips it. This is my current code:

 if bool(push_button2.read()):
 print('Please press any button when done')
 sleep(2)
 if bool(push_button1.read()) or bool(push_button2.read()):

The problem with this is if push_button1 or push_button2 is not pressed, it will move onto the next code.So is there a way to make python wait for an input via the push button? Thanks

ewokx
2,4413 gold badges20 silver badges45 bronze badges
asked Aug 5, 2020 at 6:20

1 Answer 1

2

You can use while for this:

while(!push_button2.read())
 pass

Or you can even add s small sleep() here:

while(!push_button2.read())
 sleep(0.01)

And finally, you can write your own functions:

# wait for one button
def wait_for_button(button):
 while(!button.read())
 pass
# wait for any button from a set
# usage: wait_for_any_button(button1, button2)
def wait_for_any_button(*args):
 while !any(map(lambda b: b.read(), args)):
 pass
# if you need a button index
def wait_for_any_button_i(*args):
 while True:
 for i, button in enumerate(args):
 if button.read():
 return i

https://arduino.stackexchange.com/questions/15844/pause-code-untill-a-button-is-pressed

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to make it such that ie: wait_for_button(push_button1) print('1') wait_for_button(push_button2) print('2') This is such that if button 1 is pressed, it prints'1'.If button 2 is pressed, it prints'2'.The issue I have with this function is that,referring to the code above,if button 2 is pressed before button 1, nothing is printed.In summary, the function is such that button 1 must be pressed before button 2, such that it executes.Is there a way that doesnt have this kind of flow?But really props to you man, great code!
of course, that is why I added wait_for_any_button_i function. It can tell you an index of pressed button. So that you can write: pressed = wait_for_any_button_i(button0, button1); if pressed == 0: print('Button 0 pressed!') else print('Button 1 pressed!')
I also wanted to add this if int(round(time.time())) - now == 5: buzz_pin.write(1) sleep(5) buzz_pin.write(0) break so the logic behind this is that if a button is not pressed in 5 sec, the buzzer sounds,is this possible?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.