首页 > 解决方案 > Pyboard:按下 USR 按钮时更改 LED 颜色

问题描述

我得到了这块板Pyboard D 系列,它具有三种不同颜色的内部 LED 二极管。我的目标是让它改变按钮按下时的 LED 颜色,所以基本上如果你第一次按下,红色变为红色,第二次 LED 变为绿色,第三次 LED 变为蓝色,第四次我会喜欢它(“重置”)并返回红色。

我尝试根据我在网上找到的东西制作这个功能,但它似乎没有工作。

我是 IoT 和 micropython 的新手,所以我可能会遗漏一些重要的东西,但不知道是什么。

感谢您的任何建议

from pyb import Switch
from pyb import LED


led_R = LED(1)
led_G = LED(2)
led_B = LED(3)
# 1=red, 2=green, 3=blue

sw = pyb.Switch()

def cycle():
    counter = 0
    buttonState = ''
    buttonState = sw.value()
    print(buttonState)
    if buttonState == True:
        counter = counter + 1
        print(counter)

    elif counter == 0:
        led_R.off() 
        led_G.off() 
        led_B.off() 

    elif counter == 1:
        led_R.on() 
        led_G.off() 
        led_B.off()

    elif counter == 2:
        led_R.off() 
        led_G.on() 
        led_B.off() 

    elif counter == 3:
        led_R.off() 
        led_G.off() 
        led_B.on()

    else:
        counter = 0

sw.callback(cycle())

标签: pythoncallbackswitch-statementiotled

解决方案


当按钮状态从关闭转换为打开时调用您的回调循环

在回调中 sw.value() 将始终评估为 true,因此检查它没有意义。

你的计数器应该在回调之外初始化

from pyb import Switch
from pyb import LED


led_R = LED(1)
led_G = LED(2)
led_B = LED(3)
# 1=red, 2=green, 3=blue

sw = pyb.Switch()
counter = 0

def cycle():
    counter = counter + 1
    if counter == 4:
        counter = 0
    print(counter)

    if counter == 0:
        led_R.off() 
        led_G.off() 
        led_B.off() 

    elif counter == 1:
        led_R.on() 
        led_G.off() 
        led_B.off()

    elif counter == 2:
        led_R.off() 
        led_G.on() 
        led_B.off() 

    elif counter == 3:
        led_R.off() 
        led_G.off() 
        led_B.on()


sw.callback(cycle())

推荐阅读