Strange behavior when using with and without 'for' loop inside loop()

Hi, strange behavior or I miss something.

IDE 1.6.1
Win 8.1

Arduino Uno R3

The schema attached.

pin 6,5,3 -> red, yellow, green leds

the code

int red = 6;
int green = 3;
int yellow = 5;

int colors[] = {red,yellow,green};

void setup() {
  for (int i=0;i<sizeof(colors);i++){
    pinMode(colors[i],OUTPUT);
  }
}

then the interesting thing is in loop function.
If the code is next, then the leds blinking with no problem, looped with 200ms delay, works as expected:

void loop() {
    digitalWrite(red,HIGH);
    delay(200);
    digitalWrite(red,LOW);
        
    digitalWrite(yellow,HIGH);
    delay(200);
    digitalWrite(yellow,LOW);
    
    digitalWrite(green,HIGH);
    delay(200);
    digitalWrite(green,LOW);
}

BUT, if i do like this:

void loop() {
  for (int i=0;i<sizeof(colors);i++){
    digitalWrite(colors[i],HIGH);
    delay(200);
    digitalWrite(colors[i],LOW);
  }

What basically equals to above loop() code, the delay between each led is okay, 200ms, but

  • when for loop should be repeated (new cycle in loop()) - the delay is longer, around 400ms!
  • when the very first for loop started, the last green led blinks 2 times :o .
  • after ~20sec the yellow led stays on for a second without breaking the leds cycling
  • the L smd led withing the cycles some times fade off and fade back on, and after the ~ 1 min it goes off, all (red yellow green) leds go off :o :o . At this stage the ON smd led is still on, so board has power.

Does anybody saw something like that?

20150328_131134.jpg

int colors[] = {red,yellow,green};
  for (int i=0;i<sizeof(colors);i++){
    pinMode(colors[i],OUTPUT);
  }

Your mistake is that your array of integers is 3 elements long but because the 'sizeof' operator returns the size in BYTES it is returning 6. You are running off the end of your array.

To get the length of your array:

int colors[] = {red,yellow,green};
const int COLOR_COUNT = sizeof colors / sizeof colors[0];
  for (int i=0;i<COLOR_COUNT;i++){
    pinMode(colors[i],OUTPUT);
  }