Arduino software and utilities

How to use Arrays in Arduino coding?

This entry is part 1 of 4 in the series How & Why

An array is a collection of values which are accessed with an index number. Any value in the array may be called in the program by calling the name of the array and the index number of the value.

The indexing of array starts from 0 i.e. the first value in the array begins at index number 0. An array needs to be declared and optionally assigned values before they can be used.

int arrayname[] = {value0, value1, value2...}

Likewise it is possible to declare an array by declaring the array type and size and later assign values to an index position:

int arrayname [5]; // declares integer array with 6 positions
arrayname [3] = 10; // assigns the 4th index the value 10

To retrieve or call a value from an array, assign a variable to the array and index position:

x = arrayname [3]; // x will be equal to 10

Arrays are often used in for loops, where the increment counter is also used as the index position for each array value.

The following example uses an array to flicker an LED. Using a for loop, the counter begins at 0, writes the value contained at index position 0 in the array flicker[], in this case 180, to the PWM pin 10, pauses for 200ms, then moves to the next index position.

int ledPin = 10; // LED connected to pin 10
byte flicker[] = {180, 30, 255, 200, 10, 90, 150, 60}; // array of 8 values
void setup() 
{
    pinMode(ledPin, OUTPUT); // sets OUTPUT pin
}
void loop()
{
    for(int i=0; i<7; i++) // loop equals number of values in array 
    {   
        analogWrite(ledPin, flicker[i]); // write index value
        delay(200); // pause 200ms
    }
}

Share on your network!
Prof. Dattaraj Vidyasagar
Prof. Dattaraj Vidyasagar

Author on this website. He is veteran of Core Electronics since last 36+ years. ATL Mentor of Change, Niti Ayog, Govt. of India, Google Certified Educator, International Robotics Trainer and author of 18 books on electronics, robotics, programming languages and web designing... ➤➤

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x