Arduino Arrays
Arrays An array is a collection of variables that are indexed with anindex number. An example below will help us to understand.
The key here is that each element in an array is placed directly after the previous element which allows us to access each element, in turn, using a loop function.
We can also have an array of integers, then each individual integer is referred to as an element of the array.
In an array of bytes, each element is a byte (of the Arduino byte type).
const int LEDs = 4;
const int PinLeds[LEDs] = {2,3,4,5};
// LEDs connected to pins 2-5
voidsetup()
{
for(int i=0; i < LEDs; i++ ){
pinMode(PinLeds[i], OUTPUT);
}
}
voidloop()
{
for(int i=0; i < LEDs; i++){
digitalWrite(PinLeds[i], HIGH);
delay(100);
}
for(int i=LEDs-1; i >= 0; i--){
digitalWrite(PinLeds[i], LOW);
delay(100);
}
}
We are going to go through this code and look at each part.
const int LEDs = 4;
First, we define how many elements are going to be in our array we have 4.
We use this later to make sure that we don’t try to read (or write) past the end
of our array.
const int PinLeds[LEDs] = {2,3,4,5}; or you can ommit first line
now your code will start with line below.
const int PinLeds[4] = {2,3,4,5};
// LEDs connected to pins 2-5
Next, we define the array. You’ll notice that we have the number of “ele-ments”
in the array in brackets.
We could have used the actual number, but it is much better to use a constant.
We assign the values to the array here. The values are inside of curly braces
and are separated by commas. Arrays are zero-indexed, which can be confusing.
That means the first ele-ment in the array PinLeds is PinLeds[0].
voidsetup()
{
for(int i=0; i < LEDs; i++ ){
pinMode(PinLeds[i], OUTPUT);
}
}
Here we use a for loop to go through each of the elements in our array and set
them as OUTPUT.
To access each element in the array, we use square brackets with the index inside.
for(int i=0; i < LEDs; i++) {
digitalWrite(PinLeds[i], HIGH);
delay(100);
}
This looks almost exactly the same as what is done in setup.
Here we are going through each of the LEDs and turning them on
(with a 100 millisecond delay in between them).
for(int i=LEDs-1; i >= 0; i--){
digitalWrite(PinLeds[i], LOW);
delay(100);
}
Now we are showing that we can use a for loop to go backwards through
the loop as well. We start at LEDs - 1 since arrays are zero-indexed.
If we started at LEDPins[4],
EXAMPLE 2
void setup() { int array[5]; // an array with 5 integer elements int i; // are used as an index into the array Serial.begin(9600); array[0] = 10; // assign a value of 10 to the 1st element array[1] = 102; // assign a value of 102 to the 2nd element, and many more. array[3] = 400; array[4] = 500; array[5] = 700; // display each number from the array in the serial monitor window for (i = 0; i < 5; i++) { // Accessing an Array in a Loop
Serial.println(array[i]); } } void loop() { }
Actual practical uses of arrays will be shown in project examples
Comments
Post a Comment