如何在每次按下按钮时增加 5 秒,在 micropython 中打开 LED
How to make an LED on, in micropython by adding 5 seconds each time you press a push button
你能帮帮我吗:
我想通过按下一个按钮来打开 LED,它应该保持打开状态 5 秒钟,但我希望它,如果我在它打开时按下按钮,只要时间加起来它就会保持打开状态。例如:当 LED 亮起并且我再次按下按钮时,它将亮起 10 秒钟。
我正在使用 raspberry pi pico 和 Thonny
这是我的代码:
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()
你能帮帮我吗: 我想通过按下一个按钮来打开 LED,它应该保持打开状态 5 秒钟,但我希望它,如果我在它打开时按下按钮,只要时间加起来它就会保持打开状态。例如:当 LED 亮起并且我再次按下按钮时,它将亮起 10 秒钟。 我正在使用 raspberry pi pico 和 Thonny
这是我的代码:
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()