Home ArduinoArduino Tutorials Tutorial: Arduino Arrays

Tutorial: Arduino Arrays

by shedboy71

Arrays in Arduino are used to store multiple values of the same type in a single variable. They allow you to efficiently organize and manipulate data like sensor readings, LED states, or patterns.

This tutorial covers the basics of arrays, their declaration, manipulation, and practical examples to help you master their usage in Arduino.

Table of Contents

1. What Are Arrays in Arduino?

An array is a collection of elements stored in contiguous memory locations. Arrays:

  • Allow storing multiple values of the same type.
  • Are indexed, with the first element at index 0.

2. Declaring and Initializing Arrays

Declaration

dataType arrayName[arraySize];
  • dataType: Type of data stored in the array (int, float, char, etc.).
  • arrayName: Name of the array.
  • arraySize: Number of elements in the array.

Example: Declaring an Array

int numbers[5];  // Array to store 5 integers

Initialization

Arrays can be initialized during declaration.

Example: Initialize Array with Values

int numbers[5] = {10, 20, 30, 40, 50};

Example: Automatic Size Determination

int numbers[] = {10, 20, 30, 40, 50};  // Size inferred from values

3. Accessing and Modifying Array Elements

Accessing Elements

Use the index to access elements. The index starts at 0.

Example: Access Array Elements

void setup() {
  Serial.begin(9600);

  int numbers[] = {10, 20, 30, 40, 50};
  Serial.println(numbers[0]);  // Access first element
  Serial.println(numbers[4]);  // Access last element
}

void loop() {
  // Empty
}

Modifying Elements

Assign a new value to an element using its index.

Example: Modify Array Elements

void setup() {
  Serial.begin(9600);

  int numbers[5] = {1, 2, 3, 4, 5};
  numbers[2] = 10;  // Update the third element

  Serial.println(numbers[2]);  // Print updated value
}

void loop() {
  // Empty
}

4. Iterating Through Arrays

Use loops (for or while) to iterate through an array.

Example: Print All Elements

void setup() {
  Serial.begin(9600);

  int numbers[] = {10, 20, 30, 40, 50};

  for (int i = 0; i < 5; i++) {
    Serial.println(numbers[i]);
  }
}

void loop() {
  // Empty
}

5. Multidimensional Arrays

A multidimensional array stores arrays within an array.

Declaration

dataType arrayName[size1][size2];

Example: 2D Array

int matrix[2][3] = {
  {1, 2, 3},
  {4, 5, 6}
};

Accessing Elements in a 2D Array

void setup() {
  Serial.begin(9600);

  int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
  };

  Serial.println(matrix[0][1]);  // Access the element in row 0, column 1 (2)
}

void loop() {
  // Empty
}

6. Practical Examples

6.1 Controlling Multiple LEDs

const int ledPins[] = {2, 3, 4, 5};
const int numLeds = 4;

void setup() {
  for (int i = 0; i < numLeds; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < numLeds; i++) {
    digitalWrite(ledPins[i], HIGH);  // Turn LED on
    delay(500);
    digitalWrite(ledPins[i], LOW);   // Turn LED off
    delay(500);
  }
}

6.2 Storing Sensor Readings

const int sensorPin = A0;
const int numReadings = 10;
int readings[numReadings];

void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int i = 0; i < numReadings; i++) {
    readings[i] = analogRead(sensorPin);  // Store sensor readings
    delay(100);  // Wait between readings
  }

  for (int i = 0; i < numReadings; i++) {
    Serial.println(readings[i]);  // Print all readings
  }

  delay(2000);  // Wait before taking new readings
}

6.3 LED Patterns Using 2D Arrays

const int ledPins[] = {2, 3, 4, 5};
const int numLeds = 4;
const int patterns[3][4] = {
  {1, 0, 1, 0},  // Pattern 1
  {0, 1, 0, 1},  // Pattern 2
  {1, 1, 0, 0}   // Pattern 3
};

void setup() {
  for (int i = 0; i < numLeds; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  for (int p = 0; p < 3; p++) {  // Iterate through patterns
    for (int i = 0; i < numLeds; i++) {
      digitalWrite(ledPins[i], patterns[p][i]);  // Apply pattern
    }
    delay(500);
  }
}

7. Best Practices for Using Arrays

  1. Always Define Array Size:
    • Avoid accessing elements outside the array bounds.
    int array[5];
    // Accessing array[5] is out of bounds and can cause bugs
    
  2. Use Loops for Efficiency:
    • Use loops to iterate through arrays instead of accessing each element manually.
  3. Avoid Hardcoding Array Sizes:
    • Use sizeof() to calculate the number of elements in an array.
    int array[] = {1, 2, 3, 4, 5};
    int size = sizeof(array) / sizeof(array[0]);  // Calculate array size
    
  4. Use Multidimensional Arrays When Necessary:
    • Only use multidimensional arrays if the data logically fits a grid-like structure.
  5. Test Array Indexing:
    • Verify that all indexing operations are within valid ranges to avoid unexpected behavior.

Conclusion

Arrays are a powerful tool in Arduino programming, enabling you to manage multiple values efficiently. Whether you’re controlling multiple LEDs, handling sensor data, or creating patterns, arrays make your code cleaner and more efficient. This tutorial provides a foundation for using arrays with practical examples to get you started.

For more details, visit the official Arduino reference.

 

You may also like