Reputation: 63
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
Upvotes: 1
Views: 1549
Reputation: 51
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
Upvotes: 2