This is an addition to the answer of xbox gamer (which I upvoted), to prevent much duplicated code.
For
loop
First we see, the 4 LEDs are made red or green (using green in the following case):
leds[0] = CRGB::Green;
leds[1] = CRGB::Green;
leds[2] = CRGB::Green;
leds[3] = CRGB::Green;
For this a for
loop can be used counting from 0 to (excluding) 4:
for (led = 0; led < 4; led++)
{
leds[led] = CRGB::Green;
}
Variant 1: Color argument
Next we see the first and last lines are almost identical. For this we can make a function, and change the variable items (like the color) with a variable passed to that function, which is called an argument:
First we create the loop
function:
void loop()
{
turnLEDs(CRGB::Red); // Turn LEDs on (i.e. red), then pause
turnLEDs(CRGB::Green); // Turn LEDs off (i.e. green), then pause
}
Then we need to make just a single function to change the color (place this before the loop
function. The type of the color is enum HTMLColorCode
, see http://fastled.io/docs/3.1/struct_c_r_g_b.html.
void turnLEDs(enum HTMLColorCode color)
{
for (led = 0; led < 4; led++)
{
leds[led] = color;
}
FastLED.show();
delay(5000);
}
Variant 2: Boolean argument
Another way, is to not pass the color, but pass ON or OFF, which is a boolean.
For this we can use the so-called ternary operator: a ? b : c
which means: if a
is true, use b
, otherwise c
. We get:
void turnLEDs(bool enable)
{
for (led = 0; led < 4; led++)
{
leds[led] = enable ? CRGB::Red : CRGB::Green;
}
FastLED.show();
delay(5000);
}
void loop()
{
turnLEDs(true);
turnLEDs(false);
}