Use Array to Blink More Than One Pin

I'm trying to blink more than one pin using an array. I have a little function to do this but I'm only able to blink the first 2 pins listed in the array. How can I set this up to blink the entire array?

int ledPins[3] = {3, 5, 6};       
int timer = 500;

void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT);      
  pinMode(5, OUTPUT);          
  pinMode(6, OUTPUT);          
}

void loop() {
  arrayWrite(ledPins, HIGH);
 delay (timer);
  arrayWrite(ledPins, LOW);
 delay (timer);
}

 void arrayWrite(int pins[], int val) {
    for (int i = 0; i <= (sizeof(pins)/sizeof(int)); i++) {
      digitalWrite(pins[i], val);
    } }

When you pass an array as a function argument, what actually gets passed is a pointer. The compiler has no knowledge of the length of the array - in fact, you could call it twice with different length arrays so obviously the length cannot be fixed at compilation time. Hence the sizeof() calculation on your code is not actually calculating the number of elements in your array. What it is actually doing is dividing the size of a pointer by the size of an int. On most Arduino platforms, the result will be one.

If you want arrayWrite() to support arbitrary-sized arrays, add an argument to specify the length of the array being passed in. You can calculate this length in loop() using a similar sizeof(array)/sizeof(array[0]) calculation if you like - it will work OK here since you're referring to the array variable directly and not as a formal parameter.

Also, the <= constraint in your for loop should be a <, otherwise, you will execute the loop one time too many (i.e. twice, when your sizeof() calculation indicated that the array length was one).

I don't necessarily need this to handle arbitrary lengths. How could I code it to a declared value?

Add another parameter to your function and pass in the length of the array for the function to use. The when you call the function, use the sizeof calculation as the parameter to the function.

richiep:
I don't necessarily need this to handle arbitrary lengths. How could I code it to a declared value?

    for (int i = 0; i < 3; i++) {

That did it!!! Thanks so much!

Perhaps you should also consider why it is necessary to pass a global array to a function.