Is there a better/more elegant way to just toggle an LED?

Is there a better/more elegant way to just toggle an LED? I noticed on the intro wiki the example toggle code requires setting the desired LED to CRGB::Red and then CRGB::Black:

void loop() {
      // Turn the first led red for 1 second
      leds[0] = CRGB::Red;;

      // Set the first led back to black for 1 second
      leds[0] = CRGB::Black;;

I recently used this variant:

int toggle = 0;

void loop()


      if(toggle == 1) { leds[0] = CRGB::White; }
      else { leds[0] = CRGB::Black; }
      toggle = abs(toggle - 1);;


I suppose I could just built a color array to hold CRGB::White/Black and then just switched between leds[0] = color[i]?

Anyway, just wondering how others do this. If it doesn’t already exist, I wondered about a function like this:

### or whatever other color object one wants to put in there...
leds[i] = FastLED.toggle(CRGB::Color);

Thanks for any input!

A few general techniques which might help:

If “toggle” is either 0 or 1, then this will switch it:
toggle = 1 - toggle;

Another idea is this, which doesn’t “toggle”, but rather determines the state based on the millisecond clock. I’ll assume you want a 300ms cycle, with half on and half off:
toggle = (millis() % 300) >= 150;
This will make ‘toggle’ be either zero or one, depending on the Arduino’s built-in millisecond timer.

Once you have ‘toggle’ set, here’s how you might set an LED based on it:
leds[0] = (toggle ? CRGB::White : CRGB::Black);
This should be read as “set leds[0] to… Black IF toggle is zero, or ELSE White if toggle is non-zero.”

If you want to toggle an LED between black and something else, you can do this:
leds[0] = (leds[0] ? CRGB::Black : CRGB::White);
Since a black LED is ‘false’ in this sense, this can be read as “set leds[0] to… Black IF the led is not black, or ELSE White if the led is black.”

The “(expr) ? (trueval) : (falseval)” is called the “ternary operator” or “conditional operator” and can be helpful in cases like this. It’s not a FastLED feature; it’s part of C and C++ (and other languages, too). Wikipedia has a concise description:

Which one looks good to you?

And of course combining the timer and the ? : would give this one-liner!

leds[0] = ((millis() % 300) >= 150) ? CRGB::White : CRGB::Black;

Hi @Mark_Kriegsman : sorry for the delay in responding and serious thanks for the lesson! I had no idea about those operators/functions, so I obviously have a some room to step up my C game. I’ll give them a whirl on my current project shortly.

Doing the hardware/enclosure at the moment so haven’t had a chance to dig in; hopefully this weekend/next week. Thanks for teaching me to fish :slight_smile: