问题是您的脚本需要一个循环,等待按下按钮,以便在检测到按下按钮时,您的脚本将能够对该事件做出反应。
现在,您的脚本设置了事件检测,但随后等待输入,一旦输入完成,您的脚本就会退出。
请参阅此 Raspberry Pi 论坛帖子,https://www.raspberrypi.org/forums/viewtopic.php?t=201747 https://www.raspberrypi.org/forums/viewtopic.php?t=201747
它有一个通过按下按钮来打开和关闭 LED 的程序。
然而,在我看来,如果您希望脚本在按下按钮时结束,您可能需要更改回调函数以引发异常,而不是点亮 LED。
请参阅下面修改后的程序,其中包含一些附加注释以及注释掉的 LED 灯/不亮灯。
然而,这个修改后的程序使用了一个繁忙的循环,它不断运行直到按下按钮。使用繁忙循环虽然适用于像您这样的简单程序,但通常不是一个好主意。
另一种方法是使用GPIO.wait_for_edge()
函数将暂停脚本直到按下按钮。看Raspberry Pi StackExchange - 暂停代码执行直到按下按钮 https://raspberrypi.stackexchange.com/questions/99994/pausing-code-execution-till-a-button-is-pressed这消除了繁忙的循环。
首先是繁忙循环版本。
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
btn_input = 4; # button to monitor for button presses.
LED_output = 17; # LED to light or not depending on button presses.
# GPIO btn_input set up as input.
GPIO.setup(btn_input, GPIO.IN)
# GPIO.setup(LED_output, GPIO.OUT)
# handle the button event
def buttonEventHandler_rising (pin):
# turn LED on
# GPIO.output(LED_output,True)
raise Exception('button pressed')
def buttonEventHandler_falling (pin):
# turn LED off
# GPIO.output(LED_output,False)
raise Exception('button released')
# set up the event handlers so that when there is a button press event, we
# the specified call back is invoked.
# for your purposes you may only want to detect the falling
# indicating that the button was released.
# GPIO.add_event_detect(btn_input, GPIO.RISING, callback=buttonEventHandler_rising)
GPIO.add_event_detect(btn_input, GPIO.FALLING, callback=buttonEventHandler_falling)
# we have now set our even handlers and we now need to wait until
# the event we have registered for actually happens.
# This is an infinite loop that waits for an exception to happen and
# and when the exception happens, the except of the try is triggered
# and then execution continues after the except statement.
try:
while True : pass
except:
GPIO.cleanup()
另请参阅这些论坛帖子中发生的情况的解释
https://www.raspberrypi.org/forums/viewtopic.php?t=128510 https://www.raspberrypi.org/forums/viewtopic.php?t=128510
https://www.raspberrypi.org/forums/viewtopic.php?t=141520 https://www.raspberrypi.org/forums/viewtopic.php?t=141520
这篇文章是关于 python 中的异常。https://realpython.com/python-exceptions/ https://realpython.com/python-exceptions/