[英]How to wait until you release a button in python
Is it possible to have a python script pause when you hold a button down and then start when you release that button?是否可以在按住按钮时暂停 python 脚本,然后在释放该按钮时启动? (I have the button connected to GPIO pins on my Raspberry Pi)
(我将按钮连接到 Raspberry Pi 上的 GPIO 引脚)
I am assuming that the button you are using is in GPIO18, so you can use this code.我假设您使用的按钮在 GPIO18 中,因此您可以使用此代码。
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.我认为第二个更准确地针对您的要求。
Have you looked at gpiozero ?你看过gpiozero吗? It makes interacting with GPIO much simpler.
它使与 GPIO 的交互变得更加简单。
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这是 Button 类的链接: 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以及如何使用它的示例: https : //gpiozero.readthedocs.io/en/v1.3.1/recipes.html#button
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.