我希望有人可以幫助我解決以下問題。我在 linux 上有一個帶有 GPIZero 的外部按鈕的樹莓派。我希望這樣當我按下按鈕時,python 會列印一次“按鈕被按下”,并且在我松開按鈕之前不會列印任何其他內容。當按鈕被釋放時,我希望 python 每三秒列印一次“回圈”。當我按下按鈕時,我總是希望loop()提前完成最新的功能。
所以基本上,在啟動時,python 應該一遍又一遍地列印“回圈”,直到我按下按鈕。當我按下按鈕時,該loop()程序應該在 python 列印“按鈕被按下”之前完成。然后只要我按住按鈕,就不應該列印任何其他內容。當我釋放按鈕時,它應該回到回圈“回圈”。
現在我下面的東西不起作用,但它非常接近完成我想要的。問題是這段代碼,我相信:
if button.is_pressed:
if timer ==1:
button.when_pressed = press
當我按下 timer=1 的按鈕時,我必須再次按下按鈕(非常非常快),以便它按照我描述的方式運行 press() 函式。我想按住按鈕一次press()以運行該功能。我知道它的設定是如何不穩定的。我相信button.when_pressed當它到達代碼中的那個點時,它沒有注冊按鈕已經被按下。我必須再次快速按下按鈕才能運行代碼。當它不嵌套在其他button.is_pressed部分時,我覺得它更喜歡它。但是,我不知道該怎么辦。我覺得我兩個都需要。我想保留button.when_pressed回呼,因為它只像我想要的那樣列印“按鈕被按下”一次并保持它直到我釋放按鈕,但我無法使用 If -statements 讓它自己作業。同時,button.is_pressed 在按住按鈕的同時讓 python 回圈“按下按鈕”列印,這是我不想要的。
任何幫助,將不勝感激。
#!/usr/bin/python3
from gpiozero import Button
from time import sleep
import time
button = Button(4)
timer = 0
def press():
print("Button is pressed")
def loop():
global timer
timer = 0
print('loop')
sleep(3)
timer = 1
#button.when_released = release
while True:
if button.is_pressed:
if timer ==1:
button.when_pressed = press
sleep(4)
button.when_pressed = None
else:
loop()
uj5u.com熱心網友回復:
def MainLoop():
is_pressed = False
while True:
if not is_pressed and button.is_pressed:
is_pressed = True
do_something()
else if is_pressed and not button.is_pressed:
is_pressed = False
只是保持狀態...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/399464.html
