I'm very new to this so please excuse such a basic question.... I'm trying to cross fade a RGB LED using 3 PWM pins. I am using a "for" statement within a for statement and it cross fades smoothly within the loop. But when it jumps back to the top of the loop I get a visual pulse in the LED. Any suggestions? Thanks for the help. Here's the code:
#define LED 9 //the pin for the LED
#define LED2 10 //the pin for the LED
#define LED3 11//THe last pin
int n = 0; //counting up and down
int i = 0; //we'll use this to count up and down
int w = 0;
void setup() {
pinMode(LED, OUTPUT); //tell a LED is an output
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
}
void loop() {
for(n = 255; n > 1; n--) { //loop from 0 to 254 (fade out)
analogWrite(LED, n); //set the LED brightness
for(i = 0; i < 255; i++);//Fade in
analogWrite(LED2, i);
delay (10);
}
for(i = 255; i > 1; i--) { //loop from 0 to 254 (fade out)
analogWrite(LED2, i); //set the LED brightness
for(w = 0; w < 255; w++);//Fade in
analogWrite(LED3, w);
delay (10);
}
for(w = 255; w > 1; w--) { //loop from 0 to 254 (fade out)
analogWrite(LED2, w); //set the LED brightness
for(n = 0; n < 255; n++); //Fade in
analogWrite(LED, n);
delay (10);
}
}
Last edited by adafruit_support_rick on Wed Mar 06, 2013 8:57 am, edited 1 time in total.
Reason:please use [CODE] tags
for(n = 255; n > 1; n--) { //loop from 0 to 254 (fade out)
analogWrite(LED, n); //set the LED brightness
for(i = 0; i < 255; i++);//Fade in //RESET LED2 TO 0 AND FADE IN
analogWrite(LED2, i);
delay (10);
}
for(n = 255; n > 1; n--) { //loop from 0 to 254 (fade out)
analogWrite(LED, n); //set the LED brightness
analogWrite(LED2, (255-n)); //set LED2 brightness as the complement of LED
delay (10);
}
As to your comment, I start LED (blue) at full brightness and then dim it down at the beginning of the loop. As it fades down, LED2 (green) fades in. Visually this is a smooth transition, as is the fade down of LED2 (green) and the fade up of LED3 (red). The LED3 fade down is also smooth as is the fade back up of LED (blue) at the end of the loop. At the end of the loop, LED should be back at 255, full brightness. The visual pulse happens when it goes back to the beginning of the loop, blue pulses on and off again. So I guess my question is, when the sketch runs, does it loop through the "loop" only, or does it loop through the entire sketch? (Then I would be resetting LED to 0.) Could it also be just a poor use of the "for" condition? Any help would be greatly appreciated. This is the first step in a larger project.
for(w = 255; w > 1; w--) { //loop from 0 to 254 (fade out)
analogWrite(LED2, w); //set the LED brightness
for(n = 0; n < 255; n++); //Fade in
analogWrite(LED, n);
delay (10);
}