如何在 micropython 中为按钮编写选项循环

问题描述 投票:0回答:1

我目前正在使用带有 micropython 的 Pi Pico 来编写按钮。该按钮应该使用 API 循环显示城市/国家的 11 个硬编码选项,并给出时间和温度。问题是,我一直在尝试找到适合这种情况的代码,但我最接近的是具有开/关功能的按钮。

我只有如何为按钮编写开/关功能的代码,我不知道如何循环或循环选项。我目前的按钮代码是:

button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
while True:
    first = button.value()
    time.sleep(0.01)
    second = button.value()
    if first and not second:
        print('Button pressed!')
    elif not first and second:
        print('Button released!')

我应该怎样做才能将其更改为我想要的格式?

python button micropython
1个回答
0
投票

按钮检查代码的逻辑没有多大意义。它正在寻找 10 毫秒时间内从开到关或从关到开的转换。似乎不太可能抓住任何东西。

这可能会为您提供更好的服务,具体取决于您的应用程序的其余部分:

def wait_for_button(button: machine.Pin, sleep_sec = 0.01):
    """
    idles until button is pressed and released; assumes button is configured
    such that a True return value indicates the button is pushed
    """
    while not button.value():
        time.sleep(sleep_sec)
    while button.value():
        time.sleep(sleep_sec)

要循环浏览选项列表,只需使用

itertools.cycle
:

import itertools

OPTIONS = itertools.cycle(["one", "two", "three"])

current_option = next(OPTIONS)
while True:
    # ...
    wait_for_button()
    current_option = next(OPTIONS)
    # ...
© www.soinside.com 2019 - 2024. All rights reserved.