Make blocks of 10 LEDs

Viewed 39

I want 10 red LEDs and next 10 white LEDs, and that repeated until I reach the end of the LED string.

This is the worst code, but it works.

What is the right way to do this? It must be very simple, but I can't figure it out

void Brabant() {
  for (int i = 0; i < NUM_LEDS; i = i + 20) {
    if (i < NUM_LEDS) {
      leds[i] = CRGB::Red;
      leds[i + 1] = CRGB::Red;
      leds[i + 2] = CRGB::Red;
      leds[i + 3] = CRGB::Red;
      leds[i + 4] = CRGB::Red;
      leds[i + 5] = CRGB::Red;
      leds[i + 6] = CRGB::Red;
      leds[i + 7] = CRGB::Red;
      leds[i + 8] = CRGB::Red;
      leds[i + 9] = CRGB::Red;
      FastLED.show();
    }
  }
  for (int i = 10; i < NUM_LEDS; i = i + 20) {
    if (i < NUM_LEDS) {
      leds[i] = CRGB::White;
      leds[i + 1] = CRGB::White;
      leds[i + 2] = CRGB::White;
      leds[i + 3] = CRGB::White;
      leds[i + 4] = CRGB::White;
      leds[i + 5] = CRGB::White;
      leds[i + 6] = CRGB::White;
      leds[i + 7] = CRGB::White;
      leds[i + 8] = CRGB::White;
      leds[i + 9] = CRGB::White;
      FastLED.show();
    }
  }
}
2 Answers

You could replace:

leds[i] = CRGB::White;
leds[i + 1] = CRGB::White;
leds[i + 2] = CRGB::White;
leds[i + 3] = CRGB::White;
leds[i + 4] = CRGB::White;
leds[i + 5] = CRGB::White;
leds[i + 6] = CRGB::White;
leds[i + 7] = CRGB::White;
leds[i + 8] = CRGB::White;
leds[i + 9] = CRGB::White;

with:

for (int j = 0; j < 10; j++) {
  leds[i + j] = CRGB::White;
}

Also, you need to change your i < NUM_LEDS into something safer; the loop after it could be going 10 LEDs beyond i and therefore beyond NUM_LEDS.

You could use something like this (still not "good looking but maybe a bit better)

for (int i = 0; i < NUM_LEDS; i = i + 20) {
    if (i < NUM_LEDS) {
        for (int a = 0; a < 10; a++) {
            leds[i+a] = CRGB::Red;
        }

        FastLED.show();
    }
}
for (int i = 10; i < NUM_LEDS; i = i + 20) {
    if (i < NUM_LEDS) {
        for (int a = 0; a < 10; a++) {
            leds[i+a] = CRGB::White;
        }
        FastLED.show();
    }
}

Make sure that leds[i+a] never gets bigger than the length of the leds array

Maybe something like this would also work (but not sure, I don't know the FastLED library)

for (int i = 0; i < (NUM_LEDS-20); i = i + 20) { //(NUM_LEDS-20) so that i+a+10 never gets bigger than NUM_LEDS
    if (i < NUM_LEDS) {
        for (int a = 0; a < 10; a++) {
            leds[i+a] = CRGB::Red;
            leds[i+a+10] = CRGB::White;
        }

        FastLED.show();
    }
}
Related