Reputation: 2443
I've written the following code to light up a row of LEDs one at a time.
int ledPins[] = {7,8,9,10,11,12,13};
void setup() {
for (int i = 0; i < sizeof(ledPins); i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
for (int i = 0; i < sizeof(ledPins); i++) {
digitalWrite(i, HIGH);
delay(1000);
digitalWrite(i, LOW);
delay(1000);
}
}
The above works fine. However after completing the for loop there is a long delay (about 10 seconds) before it repeats.
Why would there be such a long delay? Is this expected or is it a problem with my code?
Upvotes: 2
Views: 805
Reputation: 1615
In this case as the array has a fixed size it's simpler to do this:
#define NO_LEDS 7
int ledPins[NO_LEDS] = {7,8,9,10,11,12,13};
void setup() {
for (int i = 0; i < NO_LEDS; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
Or move the calculation of the array's size into a variable and use that.
int ledPins[] = {7,8,9,10,11,12,13};
int noLeds;
void setup() {
noLeds = sizeof(ledPins) / sizeof(int);
for (int i = 0; i < noLeds; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
Upvotes: 1
Reputation: 1786
the function sizeof(array)
return the size of the array in the memory, in bytes. and because sizeof(int)
is probably not 1, you get a larger value than expected.
sizeof
can be use to determine the number of elements in an array, by taking the size of the entire array and dividing it by the size of a single element.
so this line:
for (int i = 0; i < sizeof(ledPins); i++) {
should be rewritten as:
for (int i = 0; i < sizeof(ledPins) / sizeof(int); i++) {
see: http://en.wikipedia.org/wiki/Sizeof
Upvotes: 4