I have a simple arduino project with 5 leds, the project should start with led 1 fade through 50 millisec to reach full brightness, then led 2 and so on until led 5 then turn them all off and loop.
here is an image for the circuit (pardon the messy look my first time):
"all leds cathod are connected" and here is the code :
int led[5]={3,5,6,9,10};
// led pins array (pwm)
void setup() {
// put your setup code here, to run once:
for (int i = 0; i < 5; i++){
pinMode(led[i], OUTPUT);
}
// set each pin as an output
}
void loop() {
for (int i = 0; i < 5; i++){
int pin = led[i];
// storing the value of the current pin in a variable
int j = 0;
while(j <= 50){
j++;
delay(1);
analogWrite(pin,j*2);
}
/* the while loop is used to make the fade effect
by increasing the duty cycle by 2% each millisec
over 50 millisec */
}
delay(200);
for (int z = 5; z > -1; z--){
int pin = led[z];
analogWrite(pin,0);
}
// turning off all leds
delay(50);
}
the problem is as follows : the first round of the loop the circuit acts as expected led 1 on then 2 etc then they all turn off and loops again, on loop 16 led 1 turns off and the loop continues only with leds from 2-5 and on loop 31 led 4 and 5 turns off and only led 2 and 3 keep on going.
Edit 1 : i just found something interesting on arduino's official page (pins supporting pwm 3, 5, 6, 9, 10, 11 ) pwm frequency 490 Hz (pins 5 and 6: 980 Hz) so could the frequency result in this error?
Edit 2 : the issue was resolved with a really wierd change in the code the very first line of code " int led[5]={3,5,6,9,10};" i changed the size of the array from 5 to 6 like this " int led[6]={3,5,6,9,10};" and the issue was resolved, I discovered this while i was trying to use 4 leds and i forgot to change the size, if anyone could explain how did this change helped solve the problem ?
for (int z = 5; ...
) starts with z=5, which is an out-of-bound array index and might produce unpredictable behaviour. This also explains why your "fix" worked (you simple made the array larger). Make the loop start with z=4.