0

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.

  • 1
    One apparent problem here is that after you've gone through the `gradient` list once, `led_num` is out of range; you never seem to reset it to zero. You could write that loop as `for led_num, gradlist in enumerate(gradient):` to avoid this problem. – jasonharper Aug 23 '23 at 14:40
  • 1
    Rather than `.set_rgb(led_num, gradlist[0],gradlist[1],gradlist[2])`, it would be more convenient to express it as `.set_rgb(led_num, *gradlist)`. Also, that's not a `list` -- it's a `tuple`. – J_H Aug 23 '23 at 14:44
  • Do you have a way of knowing each _separate_ time the button is pressed, instead of just checking if the button is pressed _right now_? – John Gordon Aug 23 '23 at 14:45

1 Answers1

0

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.