0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, makes perfect sense. As a follow up, what would be an easy way to add some physics (to make the bounce of the ball feel more real)?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.