在另一个按钮调用的函数中,如何检测 gpiozero 按钮按下?

How do I detect a gpiozero Button press while in a function called by another button?

我需要通过按下按钮触发继电器并等待信号然后释放继电器。在下面的示例代码中,该信号是 b2。我是 Python 和 Pi 的新手,但玩得很开心! :)

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
from gpiozero import Button
from signal import pause
import time

def first_button():
    print("First Pressed")
    while True: #do stuff...
        time.sleep(1)
        print("waiting...")

def second_button():
    print("Second Pressed")

b1 = Button(23)
b1.when_pressed = first_button
b2 = Button(24)
b2.when_pressed = second_button

pause()

当 Button 调用的现有函数仍然 运行 时,如何检测按钮按下?

在此解决方案中,您只需打开和关闭输出

from gpiozero import Button
from signal import pause
import time

pin = #Set a pin
r = LED(pin)
b1 = Button(23)
b1.when_pressed = r.on
b2 = Button(24)
b2.when_pressed = r.off

pause()

这里启动了一个线程来做一些事情:

from gpiozero import Button
from signal import pause
import time
import _thread

run = False
def do_stuff():
    while run: #do stuff...
        time.sleep(1)
        print("waiting...")

def first_button():
    global run
    print("First Pressed")
    run = True
    _thread.start_new_thread(do_stuff)
    

def second_button():
    global run
    print("Second Pressed")
    run = False

b1 = Button(23)
b1.when_pressed = first_button
b2 = Button(24)
b2.when_pressed = second_button

pause()