Tutorial 13: How to Use Arrays with Arduino

Arduino Course for Absolute Beginners

Back in the olden days, before medical information went digital – there were medical records.  These were packets of information about when you were born, any conditions you have had, and maybe a picture of the tape worm 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 would allow a healthcare practitioner to easily find and review your case.

Well, they have the same thing in computer programs.  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 can be made easily and indexed easily.  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.  So no matter what patients record you are looking at, you know going to 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 0.  I know, weird, but highly useful as you will discover.  This is called 0 indexed.  That means is you have 5 elements in your array, the 5 element would be indexed with a 4.

Arrays can hold any thing you want – they typically hold variables.  They must be all the same type of things though.  When you declare an array, you say what the array will hold.  For example…

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

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

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

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

You can declare an initialize at the same time…

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

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

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

If you put more elements in the declaration than you use to initialize with, then empty spaces are added to the end of the array and you can put in more stuff later…

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

In this statement, the array is big enough to hold 42 dogs, but you only put in 4 to begin with.  So how do I reference that 4th dog?  What if someone asked you,  “Sir, what is the name of the fourth dog in your array?” – I get that question a ton.  You would say to that answer…

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

Remember that arrays are ZERO indexed.  So in this example:

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

myArray[0]  equals spot

myArray[1]  equals pluto

myArray[2]  equals that_big_red_dog

myArray[3]  equals ruff

Well, that is the intro on arrays, lets move onto the code and circuit to get our feet wet.

NOTE: Arrays and For Loops are like sisters who always hang out – make sure you understand For Loops from the last lesson.

You Will Need

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

Step-by-Step Instructions

If you did the last tutorial this circuit is the exact same.

  1. Connect one side of a resistor into pin 2, connect the other side into a row on the breadboard.
  2. From that row in the breadboard where you attached the resistor, connect the long leg of the LED.
  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 then your first LED.
  5. Connect an LED in the same manor – make sure the short leg goes in the SAME power strip column as the previous LED.
  6. Repeat this 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 IED.
  10. Go to File > Examples > 05.Control > Arrays
  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 sequence.
 This image created with Fritzing.

Discuss the Sketch

Here is all the code from the Arduino IDE.  I did make some minor changes from the IDE version just to make it as friendly as possible.  Try reading through this to see if makes sense…


This first piece of executable code we get to 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 variable by now, but lets tale a look at the array that is be 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 we have LEDs attached. We have left the square brackets following the name of the array empty – this means the compiler (the program integrated with the Arudino IDE that turns our human readable code into machine readable code) will count the elements in the array and this will be 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[thisPin], 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 pin count was one of the variables we declared at the top).  Every time through the 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 we want to set the mode of and 2. What mode will we set is at….

pinMode(ledPins[thisPin], OUTPUT);

So what will be the first pin mode set?  Well, what is the first index number – it will be zero, since thisPin starts at 0.  So what does ledPins[0] refer to?  Lets look back…

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

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

In this manner all the pins will get their mode set to OUTPUTs.  Once thisPin is great 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 gets incremented, we reference the array element by element.  We have more 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[thisPin], HIGH);

delay(timer);

// turn the pin off:

digitalWrite(ledPins[thisPin], LOW);

}

Imagine that, another for loop and another array!  Lets set what this one does…

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

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

The code inside the ‘for loop’ curly brackets will turn our LEDs on and off.  To do this we use the digitalWrite() function.  digitalWrite() takes two arguments – it wants to know which pin, and whether you want HIGH or LOW voltage to be written.  We tell the function which pin by using our array…

digitalWrite(ledPins[thisPin], HIGH);

The first time through the loop, the array will index as…

ledPins[0]

This will be the first element in the array which is 2.  So 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 brighten up.  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[thisPin], 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 LED “hop around” as they light up.

Now this would be well and good, but lets 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 in.

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

// turn the pin on:

digitalWrite(ledPins[thisPin], HIGH);

delay(timer);

// turn the pin off:

digitalWrite(ledPins[thisPin], LOW);

}

Lets take a close look at the statements that setup the ‘for loop':

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

thisPin is now set equal to pinCount – 1.  Keep in mind that pinCount was initialized to the value 6 at the beginning of our program.   pinCount is the number of pins we have LEDs hooked up to, 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 -1 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.

Now every time through the ‘for loop’ we decrement the thisPin variable, thus working across the array from right to left. Lets 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 };

//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 less than 0, than the loop stops.  In this way all the pins are turned on and off in reverse order.  Once this done we start at the top of loop() and go at it again.

A note on array indexing that should be discussed.  Lets 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?  Well, you and I know there is no 15th element.  We only put three elements in the array, if we try to index the 15th like so…

poundArray[14]

Well the program doesn’t like this…at all. And it while it may compile correctly – it will not operate correctly.  So 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 you 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

  • Array
  • Zero indexing
  • Nerd Fitness – I am not implying anything – this is just a great site.
Learning about Arduino?
Join the thousands to signup for our Free 12-part Arduino Video Course
We hate spam just as much as you
  • asnida

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

    • http://opensourcehardwaregroup.com/member-pages/buddypress/members/oshj/ Michael James

      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.

  • Ben

    Awesome, thanks for writing this!

    • http://www.opensourcehardwaregroup.com/ MICHAEL JAMES

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

  • agy lee

    I really enjoyed your tutorials! Very clear and too the point :-)

  • sha

    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

    • http://www.opensourcehardwaregroup.com/ MICHAEL JAMES

      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

  • Siderean

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

    • http://www.opensourcehardwaregroup.com/ MICHAEL JAMES

      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!

  • gabriel

    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