pythonloopsmicrocontrollermicropythonneopixel

Stopping a repeated for loop overloading the microcontroller


I have some RGB LEDs, and I want to draw a gradient on to them. The gradient is stored as a list of tuples, each tuple containing the R G and B values for the LEDs. I iterate through the list, and add the colour value to each respective LEDs.

gradient = [(255,255,0), (255,200,0), # and so on...
led_num = 0

while True:
    if state == 7 and toggle:
        for gradlist in gradient:
            led_strip.set_rgb(led_num,gradlist[0],gradlist[1],gradlist[2])
            led_num += 1

    if button.is_pressed:
        toggle = not toggle
        for i in range(NUM_LEDS):
            led_strip.set_rgb(i,0,0,0)

The problem with this system is that all this is inside a while loop (so you can cycle through different patterns with a button). Since I'm using micropython on a microcontroller, the board can't handle doing all that (60 times for 60 LEDs) each frame. I tried to add a variable that is disabled when the gradient has drawn, and is enabled when the gradient needs to be drawn again (i.e switching to a different pattern and switching back) but this doesn't work. That's because I have a button which can toggle the LEDs altogether, and when you click this button, the LEDs won't turn back on as it's already done drawing. Making that variable false when the button is clicked doesn't work, as the button remains clicked for a few seconds, enough for the board to overload and crash.

So, I need the if statement to only execute once, each time its conditon is met, or at least make it efficient enough to not crash the microcontroller.


Solution

  • Answer from @jasonharper

    led_num, the variable which designates which LED I was writing the colour to, was never being reset. By changing the code to this:

       if count == 7 and toggle:
            for led_num, gradlist in enumerate(gradient):
                led_strip.set_rgb(led_num,*gradlist)
    

    The led_num variable is reset to 0 each time, stopping the number from getting too high and crashing the microcontroller. Also, as suggested by @J_H, I should use *gradlist instead of gradlist[0],gradlist[1],gradlist[2], for convinience.