I'm working on a function to fade RGB LEDs smoothly from one color to the next, so I thought I'd use a for loop to increment each RGB value according with the set value. I've made the for loop as following:

``````for (redFadeCurrent, greenFadeCurrent, blueFadeCurrent;

Serial.print("Red: ");
Serial.print(" Green: ");
Serial.print(" Blue: ");
delay(3000);

redStep = -1;
}
redStep = +1;
}
else {
redStep = 0;
}

greenStep = -1;
}
greenStep = +1;
}
else {
greenStep = 0;
}

blueStep = -1;
}
blueStep = +1;
}
else {
blueStep = 0;
}
``````

Problem is, when one of the values hit the target the code leaves the for loop. I'm guessing the condition `((redFadeCurrent != redFadeTarget)&&(greenFadeCurrent != greenFadeTarget)&&(blueFadeCurrent != blueFadeTarget))` does not work.

Is there any way to work around this?

• Your code sample is incomplete the end of the loop is missing `}`. – jfpoilpret Jan 12 '15 at 5:34

You are correct, the problem is the condition inside the `for` statement.

Let's examine what happens when the red LED hits its fading target, which is, say, 100 (for the sake of the example, I will fabricate the other values):

``````for (...; (100 != 100) && (90 != 100) && (80 != 100) ; ... )
``````
• (100 != 100) -> FALSE
• (90 != 100) -> TRUE
• (80 != 100) -> TRUE

FALSE && TRUE && TRUE -> FALSE

The condition inside the `for` evaluates to `FALSE`, therefor the loop will exit.

If you want the loop to continue as long as there is at least one LED which hasn't hit the fading target, you should change the `AND` to `OR`:

``````((redFadeCurrent != redFadeTarget) || (greenFadeCurrent != greenFadeTarget) ||
``````

Let's examine what happens now with the same values:

``````for (...; (100!=100) || (90 != 100) || (80 != 100) ; ...)
``````
• (100 != 100) -> FALSE
• (90 != 100) -> TRUE
• (80 != 100) -> TRUE

FALSE || TRUE || TRUE -> TRUE ==> The loop will continue.

And what will happen when all the colors hit the fading targets?

``````for (...; (100!=100) || (100 != 100) || (100 != 100) ; ...)
``````
• (100 != 100) -> FALSE
• (100 != 100) -> FALSE
• (100 != 100) -> FALSE

FALSE || FALSE || FALSE -> FALSE ==> The loop will stop since the condition will not evaluate to `TRUE`.

• ...That's kind of embarrassing! Gotta do some exercises on my logic. :p Thank you very much! – LSSPelegrino Jan 12 '15 at 17:59