Learn to code

Arduino Home

Lessons 1
Arduino - Getting Started
Lessons 2
Arduino - Basics
Lessons 3
Arduino - Serial Communication
Lessons 4
Arduino - Digital / Analog
Lessons 5
Arduino - Visual Output
Lessons 6
Arduino - Motor Control
Lessons 7
Arduino -LCD Displays
Lessons 8
Arduino -LCD Displays

Understanding Arrays in Arduino

in Arduino Basics

The key to programming is to make a few lines of code that do as much work as possible. With efficient coding, you will save not only time but also eliminate mistakes that occur while coding.

In this tutorial, you will learn what arrays are and how to use them. In the previous tutorial about for loop() we made a sketch that blinks a LED. We learned that the for loop() is useful for repeating code. But what if we wanted 3 LEDs to blink? We could use a for loop() and repeat it for all the LEDs but that would be messy and takes a lot of code.

Creating an array that holds the pins of the LEDs will make our coding a lot easier. You will learn to do this with efficient coding in this lesson.

Arrays: are groups of the same kind of data that are placed consecutively in memory. For example, you can define an array of the data type integer. An element in an array refers to the value in the array.

Breadboard Layout

LED Pin Connections

BreadboardArduino Board
VCC5V rail
GNDGND rail
LED yellowPin10
LED redPin 11
LED greenPin 12

Example code Blink 3 LEDs

/*
   Array sketch with for loop()
   an array of 3 LEDs that blink consecutively
*/

// create array of output pins for LEDs
int ledPin[] = {10, 11, 12};

void setup()
{
  //  for loop to set all ledPins to output mode
  for (int index = 0; index < 3; index++)
  {
    // declare LED as output
    pinMode(ledPin[index], OUTPUT);

  } //close for loop()
} // close void setup()

void loop()
{

 // for loop() to blink LEDs consecutively
  for (int i = 0; i < 3; i++)
  {
     // set LEDpins HIGH
    digitalWrite(ledPin[i], HIGH);
    // add 1 second delay
    delay(1000);
    // set LEDpins LOW
    digitalWrite(ledPin[i], LOW);
  } // closing for loop()

} // close void loop()

Declaring an array

Declaring an array is similar to declaring a variable. An array needs a datatype like int (integer) and a name.

You can declare an array by using three elements: the data type of the array; the name for the array; and either a number that is surrounded by square brackets [], this is known as the index. The index tells the array how many individual variables, elements, there are in the array.

To read a particular location or element in the array, we specify the name of the array and the position number of that element in the array. It is important that each element in an array is placed directly after the previous element. This allows us to read the array according to the position of the element.

In other words, an array can be used to index data. See an array as a book. The array elements are the pages, and the numbering of the pages starts with zero (0). It may sound awkward that the counting of the numbering starts with 0.It is called zero-indexed. If an array consists of 5 elements, the fifth element would be indexed as a four (4).

Arrays can hold anything you want as long as the elements in the array are the same data type. For example:

Int ledPin[2];

This manner declares an array and tells the Arduino compiler to set aside a block of memory that we fill with data later.  In this case, we are using an int type array with had a dimension of 3 (the number of elements) that are each addressed individually by its elements index.

Arrays are 0 indexed, which means that the first position starts at 0 and the last element in the array is one less than the array’s dimension size. In our example of int ledPin[2]; the first element which index is ledPin[0] while the last element is ledPin[2];.

This ledPin array creates three separate 3 elements which can be referred to in the sketch as:

ledPin[0] = 10;
ledPin[1] = 11;
ledPin [2] = 12;

the example above assigns values to the array after we declared the array. In the example code, we declared and initialized the array at the same time. That looks like this:

Int ledPins[] = {10,11,12};

The code above does the same thing as the previous code, where we assigned all the index elements individually. However, this code takes fewer lines and is, therefore, more straightforward.

Although they function the same, There is a couple of noticeable difference between the two arrays. Firstly, the last example does not have any index. That will be fine since we initialized values to the array while we declared the array. The compiler calculates that there are 4 elements in the array and sets the array’s dimensions accordingly.

Secondly, the array’s 3 values are assigned to the array at the same time of the declaration by placing them in curly brackets { …} and separated by a comma to indicate each value. The compiler does the rest, so the first element is indexed with 0 the second with 1 until it reaches the end of the array’s initialized values.

By applying the last code above, ledPin[0] will contain the value 10, while ledPin[2] will contain the value 12. Know we know the basics of an array, let’s take a look at how to use them.

For loop() with array

Now we know how to declare an array properly, we can use an array in the sketch for setting the LEDs pin to an output mode.

the code below will set all the LEDs in the array ledPin to an output mode. This code will run once since it is nested into the void setup() part of the sketch. The index variable starts with 0 and ends with 3. Every time the index variable starts the loop, the element corresponding to the element in the array ledPin is set as an output. This allows us to turn the LEDs on.

//  for loop to set all ledPins to output mode
  for (int index = 0; index < 3; index++)
  {
    // declare LED as output
    pinMode(ledPin[index], OUTPUT);

  } //close for loop()

We could rewrite this code in the void setup() without a loop. As you can see below, this requires more coding but will have the same effect.


    pinMode(ledPin[0], OUTPUT);
    pinMode(ledPin[1], OUTPUT);
    pinMode(ledPin[2], OUTPUT);

Using the array

To read a particular location or element in the array, we specify the array’s name and the position number in the array. Each element in an array must be placed directly after the previous element. This allows us to read the array according to the position of the element.

To clarify this description, let us look at the code for an array and then apply it to an example. To turn on a LED, we can use the following code that sets pin 10 (index number 0) HIGH.

digitalWrite(ledPin[0], HIGH);

Now that we can turn on the LEDs individually by using an array, we can also loop through the array and reduce the amount of code necessary to turn on / blink the LEDs.

First, we start with a for loop initializing a variable i with a value of 0, which will be incremented each time through the loop until its value is less than 3. Each time through the loop, we call the digitalWrite() function to turn on a LED by sending a HIGH signal to that pin. As determined by the index of the array int ledPin[] the corresponding value is used given i. So the first time in the loop i equals 0, which corresponds to the led connected to pin 10. The second loop time i equals 1 and corresponds to the second element of the array, namely, pin 11.

Each time through loop(), the variable i is incremented by one to advance the array index one step moving to the next pin that is connected to a LED.

In every loop the LED will be turned on for 1 second by using the delay(1000); and then turns off by using digitalWrite(ledPin[i], LOW); before going to another LED.

 // for loop() to blink LEDs consecutively
  for (int i = 0; i < 3; i++)
  {
     // set LEDpins HIGH
    digitalWrite(ledPin[i], HIGH);
    // add 1 second delay
    delay(1000);
    // set LEDpins LOW
    digitalWrite(ledPin[i], LOW);
  } // closing for loop()

The sketch above blinks all LEDs in consecutive order. But what if we wanted to blink the LEDs (nearly) simultaneously? We can add another for loop() for that.

Simultaneously blinking

/*
   Array sketch with for loop()
   an array of 3 LEDs that blink simultaniously
*/

// create array of output pins for LEDs
int ledPin[] = {10, 11, 12};
// create a counter for blinking
int counter = 0;

void setup()
{
  //  for loop to set all ledPins to output mode
  for (int index = 0; index < 3; index++)
  {
    // declare LED as output
    pinMode(ledPin[index], OUTPUT);

  } //close for loop()
} // close void setup()

void loop()
{

  //counter for blinking 4 times
  for (counter; counter < 4; counter++)
  {
    // for loop() to turn on LEDS
    for (int i = 0; i < 3; i++)
    {
      // set corresponding pin HIGH
      digitalWrite(ledPin[i], HIGH);

    } // closing for loop()

    // add 1 second delay
    delay(1000);

    // for loop() to turn off LEDS
    for (int i = 0; i < 3; i++)
    {
      // set corresponding pin LOW
      digitalWrite(ledPin[i], LOW);

    } // closing for loop()

    // add 1 second delay
    delay(1000);

  }// close counter for loop()

} // close void loop()

In the second example, we added adjusted the code a bit so that all LEDs will blink simultaneously 4 times. To be able to do that, we added a for loop() with a variable counter. This part will run 4 times. The LEDs have blinked 1 time if the variable counter = 0. Each time through the loop, the variable counter will increment with 1 until it reaches counter = 4 and the for loop() is not executed. The variables i  will be used to go to the next element of the ledPin array index one step at a time.

//counter for blinking 4 times
  for (counter; counter < 4; counter++)

Inside the brackets, the code executes 4 times. Therefore, we need to turn the LEDs on and off within the for loop with the counter variable. First, we turn all LEDs on with the following code. When the counter variable equals one the below code is executed 4 times since the for loop() of the variable i is inside the brackets of the for loop().

// for loop() to turn on LEDS
    for (int i = 0; i < 3; i++)
    {
      // set corresponding pin HIGH
      digitalWrite(ledPin[i], HIGH);

    } // closing for loop()

After all the LEDs are turned on we add a small delay to create the blinking effect.

// add 1 second delay
    delay(1000);

After the delay() we turn the LEDs off with the code:

 // for loop() to turn off LEDS
    for (int i = 0; i < 3; i++)
    {
      // set corresponding pin LOW
      digitalWrite(ledPin[i], LOW);

    } // closing for loop()

After all the LEDs are turned off we add a small delay to create the blinking effect.

// add 1 second delay
    delay(1000);

As you can see the for loop() is pretty useful in combination with an array if we want to use values.

Further reading

Arrays can hold anything you want as long as the array elements are the same data type.

Be aware; there are some limitations concerning arrays. One important aspect is that you do not exceed access or request beyond the array’s dimension (elements declared in the array). For example, if we tried to access the fifth element in the int ledPin[3], which does not exist, we would be reading from random parts of the Arduino Memory that might be used for other things.

The compiler will not report an error if you accidentally try to store or read beyond the size of the array. You must be careful that you only access elements that are within the bounds you have set. Using a constant to set the size of an array and in code referring to its elements helps your code stay within the bounds of the array.

Arrays of characters/text.                  

Another use of arrays is to hold a string of text characters. In Arduino code, these are called character strings (strings for short). A character string consists of one or more characters, followed by the null character (the value 0) to indicate the string’s end. The null at the end of a character string is not the same as the character 0. The null has an ASCII value of 0, whereas the numeric character 0 has an ASCII value of 48.

In later tutorials, we will elaborate on this.

Hopefully, you got a better understanding of arrays after reading this lesson. As always, please leave a comment if there are unclear parts or you want to show your appreciation.

Previous Post
Understanding If / Else statement in Arduino
Next Post
Using Switch Statements in Arduino

6 Comments. Leave new

  • Richard Taylor
    16 April 2020 13:31

    “In this tutorial I have demonstrated how to use a TM1637 4-digit 7-segment display with the Arduino Uno Board. We created a count down function and two functions to display text to the display.”
    This is NOT in the Arrays tutorial!!

  • Hello,
    I have a question regarding the array:
    How can I pick a single value in the array, foe example, let’s say that I only want to turn on the LED connected to pin 7 (2nd value on the array) if a switch is high, how can I do that?

    Thank you in advance

    Nick

    • Thank you for your question, If I understand you correctly you want to press something and use the second element in the array. Remember, arrays start from 0. I hope the following code make will make you understand it a bit more.

      const int buttonPin = 2;
      int ledPins[] = { 2, 7, 10, 11};
      pincount = 4;

      void setup() {
      for (int thisPin = 0; thisPin < pinCount; thisPin++) { pinMode(ledPins[thisPin], OUTPUT); // acces the elements of the array // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); } if (digitalRead(buttonPin) == HIGH) { // turn LED on: digitalWrite(ledPins[1], HIGH); } else { // turn LED off: digitalWrite(ledPins[1], LOW);

  • Example Code 2 won’t compile as is. I modified it by moving the variable declarations above void setup () then it worked.

You must be logged in to post a comment.
Menu