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
1 Answer 1
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
3 Comments
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!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!')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?