简体   繁体   中英

LED chase using python

I am using a simple while loop and an array to chase LEDs on a strip.

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)

What would be the most elegant way to chase to the end and back repeatedly (kind of like a bouncing ball)?

Very simply, you can duplicate your for loop. Making it reversed the second time.

It appears that there is no need to redefine R, G, B over and over, so those could be moved out of the loop, but maybe you are planning to change those, so I left them in for now

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)

Ideally your API has a setLED function that you can call, Then you don't need to set the state of all of the LEDs when only 2 ever change at a time.

Instead of defining intensity as a list you could define it as a collections.deque and then 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)

and then add in an additional for loop to go back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM