如何使LED灯亮,在micropython中,每次按下按钮增加5秒



你能帮我一下吗?我想让一个LED上按下一个按钮,它应该保持5秒,但我想要它,如果我按下按钮,而它是上,它将保持上只要时间加起来。例如:当LED灯亮时,我再按一次按钮,它就会灯亮10秒。我使用树莓派pico,与thony

下面是我的代码:
from machine import Pin, Timer
import time
White_LED = Pin(15, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_DOWN) 

while True:
if button.value() == 1:
White_LED.on() 
time.sleep(5) 
White_LED.off()

当您睡眠5秒时,代码停止。所以,如果你再次按下按钮,它不会注意到。

我认为你需要使用中断处理程序(https://docs.micropython.org/en/v1.8.6/pyboard/reference/isr_rules.html),或者你可以自己实现一个简单的事件循环。

事件循环一直在寻找发生的事情,并在发生时执行一些操作。下面是你如何做的一个粗略的想法。

from machine import Pin, Timer
import time
White_LED = Pin(15, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_DOWN)
button_was = 0
light_on_until = 0
while True:
# See if the state of the button has changed
button_now = button.value()
if button_now != button_was:
button_was = button_now 
if button_now == 1:
# button is down, but it was up. 
# Increase light on time by 5 seconds
if light_on_until > time.ticks_ms():
# light is already on, increase the time by 5,000 ms
light_on_until += 5000
else:
# light isn't on, so set time to 5 seconds from now (5,000 ms)
light_on_until = time.ticks_ms() + 5000
if light_on_until > time.ticks_ms():
# light should be on, so if it's currently off, switch it on        
if White_LED.value() == 0:
White_LED.on()
else:
# light should be off, so if it's currently on, switch it off
if White_LED.value() == 1:
White_LED.off()

最新更新