SALES INQUIRIES: 1 (888) 767-9864

Tutorial 13: How to Use Arrays with Arduino

Arduino Course for Absolute Beginners

How to Use Arrays with Arduino

Back in the old days, before medical information went digital – there were paper medical records. These were packets of information about when you were born, any conditions you have had, and maybe a picture of the tapeworm they pulled out of your belly in high school. The purpose of the record was to organize information about your medical history in a way that allowed a healthcare practitioner to easily find and review your case.

Computer programs can organize information in a similar way. These records are called data structures – they are organized ways of storing data. One immensely handy data structure is the array. Arrays rock because they are easily created and indexed.

Indexing is how you find the information in your data structure. With the medical record example, it might be that all your immunizations are listed on page 5. No matter what patient record you review, you know page 5 will provide their immunization data.

An array has multiple elements – which would be the equivalent of pages in a medical record. The first page starts at zero.

If it seems strange to start the count at zero, don’t worry, you are not alone. It is weird at first, but highly useful as you will discover. This is called zero indexed. That means if you have 5 elements in your array, the 5th element would be indexed with a 4.

Arrays can hold anything you want as long as the contents are the same data type. When you declare an array, you say what the array will hold. For example:

int myArray[]; //this array will hold integers

dogs myArray[]; // this array will hold dogs

To initialize an array (put stuff in it), all you have to do is the following:

myArray[] = {spot, pluto, clifford, ruff};

You can declare and initialize at the same time:

dogs myArray[] = {spot, pluto, clifford, ruff};

If you want, you can specify the number of elements in your array when you declare it:

dogs myArray[4] = {spot, pluto, clifford, ruff};

If you put more elements in the declaration than you use to initialize, empty spaces are added to the end of the array and you can add things later:

dogs myArray[42] = {spot, pluto, clifford, ruff};

In this statement, the array is big enough to hold 42 dogs, but you only put in 4 to begin with, so you have 38 more dogs you could add later.

So how do I reference that 4th dog? What if someone asked you, “Monsieur, what is the name of the fourth dog in your array?” – I get that question a ton. You would respond:

myArray[3]; // this refers to the 4th element in the array

Remember that arrays are ZERO indexed. In this example:

dogs myArray[4] = {spot, pluto, clifford, ruff};

myArray[0] equals spot

myArray[1] equals pluto

myArray[2] equals clifford

myArray[3] equals ruff

OK, that is the intro on arrays, let’s move on to the code and circuit to get our feet wet.

NOTE: arrays and for loops are like sisters who always hang out – to best comprehend this section, make sure you understand for loops from the previous lesson.

Array Explanation Demo

You Will Need

  1. LED (6)
  2. 220-Ohm Resistor (6)
  3. Jumper Wires (1)
  4. Dog leash (1)

Switch Case Board 2

 This image created with Fritzing.

The Arduino Code

/*
  Arrays

 Demonstrates the use of  an array to hold pin numbers
 in order to iterate over the pins in a sequence.
 Lights multiple LEDs in sequence, then in reverse.

 Unlike the For Loop tutorial, where the pins have to be
 contiguous, here the pins can be in any random order.

 The circuit:
 * LEDs from pins 2 through 7 to ground

 created 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Array
 */

int timer = 100;           // The higher the number, the slower the timing.
int ledPins[] = {
  2, 7, 4, 6, 5, 3
};       // an array of pin numbers to which LEDs are attached
int pinCount = 6;           // the number of pins (i.e. the length of the array)

void setup() {
  // the array elements are numbered from 0 to (pinCount - 1).
  // use a for loop to initialize each pin as an output:
  for (int thisPin = 0; thisPin < pinCount; thisPin++) {
    pinMode(ledPins, OUTPUT);
  }
}

void loop() {
  // loop from the lowest pin to the highest:
  for (int thisPin = 0; thisPin < pinCount; thisPin++) {
    // turn the pin on:
    digitalWrite(ledPins, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(ledPins, LOW);

  }

  // loop from the highest pin to the lowest:
  for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) {
    // turn the pin on:
    digitalWrite(ledPins, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(ledPins, LOW);
  }
}

Step-by-Step Instructions

If you did the previous tutorial this circuit is exactly the same.

  1. Connect one side of a resistor into pin 2, connect the other side into a row on the breadboard.
  2. Connect the long leg of the LED to the row in the breadboard where you attached the resistor.
  3. Connect the short leg of the LED to one of the power strip columns on your breadboard.
  4. Now connect a resistor to pin 3, and put the other leg in a row on the breadboard (a different one than your first LED).
  5. Connect an LED in the same manner – make sure the short leg goes in the SAME power strip column as the previous LED.
  6. Add LEDs and resistors in this fashion through pin 7.
  7. Using a jumper wire, connect the common power strip to a GND pin on the Arduino.
  8. Connect the Arduino to your computer.
  9. Open up the Arduino IDE.
  10. Open the sketch for this section.
  11. Click the Verify button (top left). The button will turn orange and then blue once finished.
  12. Click the Upload button. The button will turn orange and then blue when finished.
  13. Watch in awe as your LEDs turn on and off in a mixed sequence.

Discuss the Sketch

This first piece of executable code is the declaration and initialization of variables:

int timer = 100;           // The higher the number, the slower the timing.

int ledPins[] = { 2, 7, 4, 6, 5, 3 };       // an array of pin numbers to which LEDs are attached

int pinCount = 6;           // the number of pins (i.e. the length of the array)

You should be very familiar with how to declare and initialize integer variables by now, but let’s take a look at the array that is being made:

int ledPins[] = { 2, 7, 4, 6, 5, 3 };       // an array of pin numbers to which LEDs are attached

This is an array that will hold integers as the preceding int tells us. Keep in mind that the elements in this array represent pins where LEDs are attached. We have left the square brackets following the name of the array empty – this means the compiler (the program integrated with the Arduino IDE that turns our human readable code into machine readable code), will count the elements in the array and set its size – in this case it as an array of 6 elements (count them, I dare you!). The name of the array can be whatever you like; descriptive names are always good.

The next block of code is the setup() function. Here we assign pin modes using a combination of our array and a for loop:

void setup() {

    for (int thisPin = 0; thisPin < pinCount; thisPin++) {

       pinMode(ledPins, OUTPUT);

    }

}

Ok, what’s going on here? We have a for loop, the condition is:

thisPin < pinCount

We can see that thisPin is initialized at 0 and pinCount is equal to 6 (recall that pinCount was one of the variables we declared at the top). Every time through the for loop, thisPin is incremented by adding 1.

The code executed in the curly brackets makes use of our array and uses thisPin as the index counter. The function is our old friend pinMode() which takes two arguments 1) Which pin to set the mode and 2) What mode we set:

pinMode(ledPins, OUTPUT);

To determine the outcome of this line of code recall that the value of thisPin was set to zero. So what does ledPins[0] refer to?

Let’s look back…

int ledPins[] = { 2, 7, 4, 6, 5, 3 }; 

                  0, 1, 2, 3, 4, 5 index of each element

Since zero indexes the first element of the array, it appears that pin 2 will be the first pin to get its mode set to an OUTPUT. The next time through the for loop, the variable thisPin will equal 1 (since it is incremented each time through the for loop). What will ledPins[1] refer to? Pin 7, since pin 7 is the second element in the array.

All the pins will get their mode set to OUTPUTs in this manner. Once thisPin is greater than 5, the for loop will stop. So now you have gotten a taste of using a for loop and an array together. The counter variable of the for loop acts as the indexing number for the array. As the counter variable is incremented, we reference the array element by element. We will have another chance to see this union in the loop().

The first block of code in loop() is:

for (int thisPin = 0; thisPin < pinCount; thisPin++) {

    // turn the pin on:

   digitalWrite(ledPins, HIGH);

   delay(timer);

   // turn the pin off:

   digitalWrite(ledPins, LOW);

}

Imagine that – another for loop and another array! Let’s see what this one does…

We have the exact same statements in the for loop as before – we set thisPin equal to 0, the condition is thisPin < pinCount, and we increment thisPin by 1 each time through the for loop:

for (int thisPin = 0; thisPin < pinCount; thisPin++)

The code inside the for loop curly brackets will turn the LEDs on and off. To do this, we use the digitalWrite() function. Recall digitalWrite() takes two arguments 1) it wants to know which pin and 2) whether you want HIGH or LOW voltage applied. We tell the function which pin by using an array:

digitalWrite(ledPins, HIGH);

The first time through the for loop, the array will index as:

ledPins[0]

This is the first element in the array which is the number 2. Now the LED at pin 2 will turn on because we are applying 5 volts to that pin. If we fast forward to the next time we come to this function, thisPin will have been incremented, and the value of thisPin will be 1 as follows:

ledPins[1]

This will digitalWrite() to the second element in the array, which is 7. So our LED at pin 7 will turn on. But I am getting ahead of myself. First we have to enjoy the brightness, to do this we delay the program:

delay(timer);                  //Nothing new here

Now we want to turn off the LED. The function is the exact same, we just write LOW voltage to the pin:

digitalWrite(ledPins, LOW);

This continues through the for loop turning each LED referred to in the array on and off. Note that since the pin numbers in the array are not sequential, the LEDs “hop around” as they light up.

Now this would be well and good, but let’s keep it interesting and start at the last element in the array and move to the first element – reversing the order the LEDs turn on and off.

for (int thisPin = pinCount – 1; thisPin >= 0; thisPin--) {

    // turn the pin on:

    digitalWrite(ledPins, HIGH);

    delay(timer);

    // turn the pin off:

    digitalWrite(ledPins, LOW);

}

Let’s take a close look at the statements that set up the next for loop:

for (int thisPin = pinCount – 1; thisPin >= 0; thisPin--)

thisPin is now initialized to pinCount-1 (pinCount minus one). Keep in mind that pinCount was initialized to the value 6 at the beginning of our program. pinCount is the number of pins where LEDs are attached, and it is also the size of the array. But if we want to access the last element in the array, we need to start at pinCount minus one (because of our 0 index). This is peculiar at first, but after you write a couple for loops with arrays, it will be a snap.

Every time through the for loop we decrement the thisPin variable, thus working across the array from right to left. Let’s take a look at the actual values as we work through the for loop:

As a reminder, this is what we stored in our array:

ledPins[] = { 2, 7, 4, 6, 5, 3 };

              0, 1, 2, 3, 4, 5 index of each element

//First time through

ledPins[5] <=> this is the sixth element in the array, which is the value 3

//Next time through the for loop – remember that thisPin is decremented…

ledPins[4] <==> the 5th element in the array is 5

//Next time through the for loop

ledPins[3] <==> the 4th element in the array is 6

//Next time through the for loop

ledPins[2] <==> the 3rd element in the array is 4

I think you get the picture. When thisPin gets decremented to less than 0, than the for loop stops. In this way, all the pins are turned on and off in reverse order. Once this is done we start at the top of the loop() and go at it again.

A final note about array indexing – let’s say you put 3 elements in an array…

dogs poundArray[3] = {Spike, Scooby, Lassie};

…but then you try to get the 15th element in that array. You and I know there is no 15th element. We only put three elements in the array, if we try to index the 15th element:

poundArray[14]

The program doesn’t like this…at all. And while it may compile correctly – it will not operate correctly. If your program starts acting all funky – or not acting at all – check your index and make sure you didn’t index outside the size of the arrays.

Try On Your Own

  • Switch up the order of the values in the ledPins[] Array. Make sure you use the same values, just change the order.
  • Add an additional LED at pin 8. Adjust the ledPins[] array and all three for loop statements accordingly.

Further Reading

34 Comments

  1. Avatar asnida on March 1, 2013 at 4:38 am

    Hi,
    Typo > The decrement sign should be ” — ”
    Thanks



    • Avatar oshj on March 1, 2013 at 9:24 am

      Thanks Asnida!

      It appears my website theme is rendering a double dash as a single line. I went and put a a space between the dashes. Thanks for pointing that out. I will probably have to make similar changes elsewhere.



  2. Avatar Ben on February 1, 2014 at 10:55 pm

    Awesome, thanks for writing this!



    • Avatar MICHAEL JAMES on February 1, 2014 at 11:02 pm

      Glad it helped. Let me know if you need more clarity on any items.



  3. Avatar agy lee on April 18, 2014 at 11:25 pm

    I really enjoyed your tutorials! Very clear and too the point 🙂



  4. Avatar sha on September 30, 2014 at 8:07 am

    is it possible to use several members of an array in one line?
    meaning: MyArray[] = {1,2,3,4,5,6};
    pinMode(MyArray[0,2,4],OUTPUT);
    thanks



    • Avatar MICHAEL JAMES on September 30, 2014 at 8:40 am

      Hi Sha, no its not – but, if you use a “for loop”, you can set the modes of all the pins in a similar fashion.

      for(int i = 0; i < 5; i = i + 2){
      pinMode(MyArray[i], OUTPUT);
      }//close for



  5. Avatar Siderean on October 21, 2014 at 1:31 pm

    “int myArray[];” gives me the error: storage size of ‘myArray’ isn’t known.



    • Avatar MICHAEL JAMES on October 21, 2014 at 6:00 pm

      The way I presented that first part was not correct. If you leave the array size indeterminate by keeping the brackets empty (like in your example), then you need to initialize the array inside the curly brackets with the number of elements you want. Like this:

      int myPins[] = {2, 4, 8, 3, 6};

      I gave the impression in the video that you can dynamically size the array throughout the program, but you cannot. The size of the array needs defined when it is declared (though it does not need to be initialized with all of it’s elements, you can fill those spots later.)

      Sorry about the confusion, I hope that helps!



  6. Avatar gabriel on October 29, 2014 at 5:58 pm

    hi,

    I’m not sure where to look for, but I’m looking to create a project where;
    if i have 4 ppl with 4 switch, attached to an Arduino that transmit signal using RF. the receiver will receive the signal accroding to the order the switch has been triggered.
    Example; If switch was triggered by order of 2,3,1,4…….this will send signal to a LCD Display/LED to show who send the 1st signal (Switch 2) and will ONLY show the 2nd (switch 3) when the 1st signal (Switch 2) is switched OFF.

    Your help will be greatly appreciated….thank you



  7. Avatar Bishal Basnet on November 15, 2014 at 5:18 am

    Can i access multiple values from a array at once and use it with if statement to perform certain tasks such as running motors etc i tried it like this Is that okay please have a look:

    int sensor[7] = { 8,9,10,11,12,13,14 };
    int sensorReading[7] = { 0 };
    void setup()
    {
    for(int i=0; i<7; i++) {
    pinMode(sensor[i], INPUT);
    void readSensor(void) {
    {
    void loop()
    void readSensor(void) {
    for(int i=0; i<7; i++)
    {
    sensorReading[i] = digitalRead(sensor[i]);
    if((sensor[i])) == 0011000{
    void motorrun(void){………..



    • Avatar MICHAEL JAMES on November 15, 2014 at 11:03 pm

      Hi Bishal,

      I think the core of what you are asking comes down to this line of code:

      “if((sensor[i])) == 0011000”

      Unfortunately it wouldn’t work like that. You would have to compare each element in the array one at a time with another known array.

      You might be able to convert the array to string, and then make a comparison like that.

      Best of luck!



      • Avatar Bishal Basnet on November 16, 2014 at 12:15 am

        Please can you help me how to convert array to string and compare all elements at once. I mean a simple example on how to do it.



        • Avatar MICHAEL JAMES on November 17, 2014 at 9:42 am

          I will see what I can put together for you!



          • Avatar Bishal Basnet on November 17, 2014 at 11:19 am

            I will be very thankful to you. Actually I want this for my science project so would you mind to do it faster please. Because my end dates of this project is coming soon. It is really really important to me.



  8. Avatar Robert on March 13, 2016 at 6:02 am

    This is incredibly helpful. Thank you. I am really puzzled by one line of code though:

    for (int thisPin = 0; thisPin < pinCount; thisPin++)

    Why doesn't the thisPin++ command follow the digitalWrite lines rather than come before it?

    As it stands, the code sets the thisPin to 0, then checks if it is less than 6 and if it isn't it then adds 1 to the thisPin number – before switching the LED on then off.

    It looks like thisPin would already move to 1 before the first run of the loop? So the first pin in the array would be missed out.

    Surely it would have to read "thisPin = -1" in order to move to 0 (1st array item) for the first run of the loop? Alternatively, if the increment to thisPin followed the LED on/off code then the first item in the array would not be skipped.

    I appreciate that the code isn't wrong, it is my lack of understanding, but would really appreciate if anyone can put me right on this. Best wishes and thank you, Robert



    • Avatar Guz Forster on March 15, 2016 at 1:30 pm

      It’s not checking if it ISN’T less than 6, it’s checking if it IS less than 6 – and then if it is, it will add 1 to it until the condition is false… 🙂



      • Avatar Robert on March 15, 2016 at 6:34 pm

        Thanks, Guz. I am being thick here I know but…

        So, it would like this:

        1. thisPin = 0
        2. 0 is less than 6?
        3. True, so add 1 to thisPin
        4. thisPin now = 1
        5. Light the LED whose number corresponds to 1 (the *second* number in array)
        6. thisPin = 1
        7. 1 is less than 6?
        8. True, so add 1 to thisPin
        9. thisPin now = 2
        10. Light the LED whose number corresponds to 2 (the third number in array)

        …and so on till condition false.

        I have tried putting in a serial monitor and slowing it down and I can see that in fact the script does not skip the first number in the array. I have also tried moving thisPin++; out of the brackets and putting it after the LED light command, and the print out is exactly the same. So this leaves me even more perplexed! Why doesn’t the code add 1 to the thisPin variable on the first run of the loop?



        • Avatar MICHAEL JAMES on March 15, 2016 at 9:36 pm

          Hi Robert,

          The video doesn’t do a stellar job of explaining, but the incrementation does not happen until after the loop has been completed once. I hope this helps.



          • Avatar Robert on March 16, 2016 at 6:23 pm

            Thanks Michael – it does explain everything. Much appreciated.



        • Avatar Guz Forster on April 13, 2016 at 12:51 am

          Hi, sorry it took me so long to answer! So where are you placing this Serial.print? I’m asking because in the end of the loop it actually starts to subtract from thisPin, so you wouldn’t see “1” in the end of the code. Also, you using the exact same code as provided? If not, care to paste your code here so I can take a look?



  9. Avatar Skatefish on March 29, 2016 at 4:51 am

    Hi. How to save phone number in array? I want to save the phone number from the incoming SMS.



    • Avatar MICHAEL JAMES on March 30, 2016 at 11:23 pm

      I suppose it depends on how you get the incoming phone number – is it a text string? or a long data type? Or do you get the numbers one at a time?

      If you get them one at a time, you can just add them number by number to an array, if you get it is a text string, than you may be able to parse it piece by piece into the array.

      Best of luck!



      • Avatar Skatefish on April 26, 2016 at 4:22 am

        can you do a tutorial on this?



        • Avatar Skatefish on April 26, 2016 at 4:23 am

          or do you have a tutorial that nearly the same with the problem?



  10. Avatar Alaa Elsaid on June 4, 2016 at 5:43 pm

    if i wanna to put ledPins[thisPin] in a variable what should i do like pin = ledPins[thisPin];



  11. Avatar Muhammed Atef Abdoullah on June 13, 2016 at 8:31 pm

    I’m on a security lock project right now , I need to delete one character from the array of data written on lcd . how is that possible i thought in decrementing the size of array ? is that right ? if not what is the solution ,, hope for a quick response



  12. Avatar malak gouiaa on March 24, 2017 at 6:19 pm

    can i use buttons not a leds?? if yes, how can i do it?



  13. Avatar jessica on May 29, 2017 at 6:54 pm

    Thank you geniuses. Great explanation.



  14. Avatar jessica on May 29, 2017 at 6:55 pm

    “Any fool can make something complicated. It takes a genius to make it simple.”
    you made it simple to understand and there is no doubt that you guys are genius. Great work, keep it up.



    • Avatar MICHAEL JAMES on May 30, 2017 at 12:08 pm

      Thanks a ton! But I assure you – I am no genius!



  15. Avatar Michael Salais on February 12, 2018 at 4:55 pm

    How about 2D arrays? I’m trying to control an 8×8 led array. Seems like a natural for arrays commands. Do you have to make two single arrays?