1

I'm trying to pause code execution till a button is pressed and this is what I came up with. I have not tested this but can anyone tell me if this is the right way to go about it? Button 'pressed' is active HIGH on the GPIO pin.

import RPi.GPIO as GPIO
GPIO.setmode (GPIO.BOARD)
#BCM uses the GPIO numbers while BOARD uses the actual pin number
GPIO.setwarnings (False)

while GPIO.input(17) == False:
    pass

print ("Button 1 pressed")

GPIO.cleanup()
  • 2
    Busy looping is the equivalent of sitting in a parked car with the accelerator held to the floor -- a bad thing unless necessary, which it isn't in this case -- you want the program to wait idling, by throwing a brief sleep inside the loop (for human interaction, say 0.1-0.25 seconds). Otherwise it just checks the condition as fast as it can, likely hogging 100% of a processor core. – goldilocks Jun 26 at 18:44
  • I have not tested this ... why not? ... that is all part of research that you should have done before posting your question – jsotola Jun 26 at 21:52
3

That's one way of doing it - it will work. The better way is to use GPIO.wait_for_edge(17, GPIO.RISING) which will pause at that line until the button is pressed (on a RISING or FALLING edge).

However, BOARD numbering pin 17 is not a GPIO, it's 3V3.

You could also use GPIO Zero which is more intuitive (and uses BCM numbering):

from gpiozero import Button

btn = Button(17)

btn.wait_for_press()
print("Button pressed")

You can use Button(17, pull_up=False) if it's pulled down, and the "pressed" state is relative to that.

https://gpiozero.readthedocs.io/en/stable/

  • 1
    "wait for press" probably includes some debouncification, a good thing since you very likely might end up having to implement it to some extent in the manual loop anyway, or else suffer the onoffonoffonoff chatter. – goldilocks Jun 26 at 18:48
  • Thanks! This is helpful. It should be 11 and not 17 since the board number is used. – electrophile Jun 27 at 1:12
  • @goldilocks There is hardware debouncing built onto my breakout board as described here. Except in my case, the button and the 10k positions are switched making this active high. Nonetheless, I agree with you on the importance of debouncing. – electrophile Jun 27 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.