I am working through the Arduino Starter kit manual on project 5 which introduces arrays.
the code:
// Project 5 - LED Chase Effect
// Create array for LED pins
byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int ledDelay(65); // delay between changes
int direction = 1;
int currentLED = 0;
unsigned long changeTime;
void setup() {
// set all pins to output
for (int x=0; x<10; x++) {
pinMode(ledPin[x], OUTPUT); }
changeTime = millis();
}
void loop() {
// if it has been ledDelay ms since last change
if ((millis() - changeTime) > ledDelay) {
changeLED();
changeTime = millis();
}
}
void changeLED() {
// turn off all LED's
for (int x=0; x<10; x++) {
digitalWrite(ledPin[x], LOW);
}
// turn on the current LED
digitalWrite(ledPin[currentLED], HIGH);
// increment by the direction value
currentLED += direction;
// change direction if we reach the end
if (currentLED == 9) {direction = -1;}
if (currentLED == 0) {direction = 1;}
}
The code is fine but In Mc Robert's code explanation (which I set in italics)I think there is an error:
Our very first line in this sketch is
byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12,
13};
and this is a declaration of a variable of data type
array. An array is a collection of variables that are
accessed using an index number. In our sketch we
have declared an array of data type byte and called it
ledPin. We have then initialised the array with 10
values, which are the digital pins 4 through to 13. To
access an element of the array we simply refer to the
index number of that element. Arrays are zero
indexed, which simply means that the first index starts
at zero and not 1. So in our 10 element array the index
numbers are 0 to 9.
In this case, element 3 (ledPin[2]) has the value of
6 and element 7 (ledPin[6]) has a value of 10.
You have to tell the size of the array if you do not
initialise it with data first. In our sketch we did not
explicitly choose a size as the compiler is able to
count the values we have assigned to the array to
work out that the size is 10 elements. If we had
declared the array but not initialised it with values at
the same time, we would need to declare a size, for
example we could have done this:
byte ledPin[10];
and then loaded data into the elements later on. To
retrieve a value from the array we would do something
like this:
x = ledpin[5];
in this example x would now hold a value of 8.
The last statement "in this example x would now hold a value of 8" seems incorrect. If I am understanding this correctly If arrays are zero indexed then x should hold a value of 9 not 8. This is why in the example when the arrays were initialized "(ledPin[2]) has the value of 6" . I am new to this, only a few weeks in so I could be off somewhere.
Experienced programers please chime in!