使用python的LED追逐

2024-06-25 22:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了一个简单的while循环和一个数组来追踪条带上的led。你知道吗

while True:
    for i in range(nLEDs):
        R = [ 255 ] * nLEDs
        G = [ 255 ] * nLEDs
        B = [ 255 ] * nLEDs
        intensity = [ 0 ] * nLEDs
        intensity[i] = 1
        setLEDs(R, G, B, intensity)
        time.sleep(0.05)

什么是最优雅的方式追逐到底,并反复回来(有点像一个弹跳球)?你知道吗


Tags: intrueforledtime方式rangesleep
2条回答

与其将强度定义为列表,不如将其定义为collections.deque然后rotate

R = [ 255 ] * nLEDs
G = [ 255 ] * nLEDs
B = [ 255 ] * nLEDs
intensity = collections.deque([ 0 ] * nLEDs)
intensity[0] = 1
while True:
    for i in range(nLEDs):
        intensity.rotate(1)
        setLEDs(R, G, B, list(intensity))
        time.sleep(0.05)

然后添加一个额外的for循环返回

非常简单,您可以复制for循环。第二次倒过来。你知道吗

似乎没有必要一次又一次地重新定义R,G,B,这样它们就可以从循环中移出,但是也许你正计划改变它们,所以我暂时把它们留在了循环中

while True:
    for i in range(nLEDs):
        R = [ 255 ] * nLEDs
        G = [ 255 ] * nLEDs
        B = [ 255 ] * nLEDs
        intensity = [ 0 ] * nLEDs
        intensity[i] = 1
        setLEDs(R, G, B, intensity)
        time.sleep(0.05)

    for i in reversed(range(nLEDs)):
        R = [ 255 ] * nLEDs
        G = [ 255 ] * nLEDs
        B = [ 255 ] * nLEDs
        intensity = [ 0 ] * nLEDs
        intensity[i] = 1
        setLEDs(R, G, B, intensity)
        time.sleep(0.05)

理想情况下,API有一个可以调用的setLED函数,当一次只有2个led发生变化时,就不需要设置所有led的状态。你知道吗

相关问题 更多 >