0
0
AutocadHow-ToBeginner · 3 min read

How to Use Arrays in Arduino: Syntax and Examples

In Arduino, you use arrays to store multiple values of the same type in a single variable. Declare an array with a type, name, and size like int numbers[5];, then access elements by their index starting at 0.
📐

Syntax

An array in Arduino is declared by specifying the data type, the array name, and the number of elements inside square brackets. You can also initialize it with values inside curly braces.

  • Data type: The type of values stored (e.g., int, float, char).
  • Array name: The variable name for the array.
  • Size: Number of elements the array can hold, fixed at declaration.
  • Index: Position of an element, starting at 0.
arduino
int numbers[5];

// or with initialization
int numbers[5] = {10, 20, 30, 40, 50};
💻

Example

This example shows how to declare an array, assign values, and print each element using a loop.

arduino
#include <Arduino.h>

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

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < 5; i++) {
    Serial.print("Element ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(numbers[i]);
  }
}

void loop() {
  // Nothing here
}
Output
Element 0: 10 Element 1: 20 Element 2: 30 Element 3: 40 Element 4: 50
⚠️

Common Pitfalls

Common mistakes when using arrays in Arduino include:

  • Accessing indexes outside the array size (e.g., numbers[5] when size is 5, valid indexes are 0 to 4).
  • Not initializing arrays before use, which can cause unpredictable values.
  • Using the wrong data type for the array elements.

Always ensure your index is within bounds and initialize arrays properly.

arduino
int numbers[3] = {1, 2, 3};

void setup() {
  Serial.begin(9600);
  // Wrong: accessing out of bounds
  // Serial.println(numbers[3]); // This is invalid and may cause errors

  // Correct:
  for (int i = 0; i < 3; i++) {
    Serial.println(numbers[i]);
  }
}

void loop() {}
Output
1 2 3
📊

Quick Reference

  • Declare: type name[size];
  • Initialize: type name[size] = {val1, val2, ...};
  • Access: Use name[index] where index starts at 0.
  • Size: Fixed at declaration, cannot be changed later.
  • Loop: Use for loops to iterate over arrays.

Key Takeaways

Declare arrays with a fixed size and a single data type in Arduino.
Access array elements using zero-based indexes inside valid bounds.
Initialize arrays to avoid unpredictable values.
Use loops to process all elements efficiently.
Avoid accessing indexes outside the declared array size.