Reputation: 11
Is it possible to have a python script pause when you hold a button down and then start when you release that button? (I have the button connected to GPIO pins on my Raspberry Pi)
Upvotes: 1
Views: 3960
Reputation: 827
Have you looked at gpiozero? It makes interacting with GPIO much simpler.
from gpiozero import Button
button = Button(2)
button.wait_for_press()
button.wait_for_release()
print("Button was pressed and released")
Here's the link to the Button class: https://gpiozero.readthedocs.io/en/v1.3.1/api_input.html#gpiozero.Button.wait_for_release
And examples of how to use it: https://gpiozero.readthedocs.io/en/v1.3.1/recipes.html#button
Upvotes: 1
Reputation: 69755
I am assuming that the button you are using is in GPIO18, so you can use this code.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
input_state = GPIO.input(18)
while not input_state:
# as soon as your button is pressed you
# will be inside this loop
print('Button is being pressed')
Alternatively you can also try:
import time
import RPi.GPIO as GPIO
PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
GPIO.wait_for_edge(PIN, GPIO.FALLING)
print "Pressed"
# your code
I think the second targets more precisely your request.
Upvotes: 1