Search code examples
pythonled

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)?


Solution

  • 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.