Arrays in Arduino: Handling Multiple Values Easily

Using Arrays in Arduino: Handling Multiple Values Easily

When you start working on Arduino projects, sooner or later you’ll need to store a bunch of similar values — maybe sensor readings, LED states, or motor positions. Instead of creating a dozen separate variables, you can make your life much easier by using arrays.

Arrays are like containers that hold a list of values. You can think of them as labeled storage boxes, each with its own little compartment. Let’s take a look at how arrays work and why they’re so useful.


🧠 What Is an Array?

An array is a single variable that can hold multiple values of the same type.
Here’s what it looks like in Arduino code:

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

This creates an array named numbers that holds five values.
Each value can be accessed using an index number — starting from 0.

So:

  • numbers[0] gives you 10
  • numbers[1] gives you 20
  • numbers[4] gives you 50

💡 Why Use Arrays?

Arrays are great because they simplify your code.

Instead of this:

int led1 = 2;
int led2 = 3;
int led3 = 4;

You can write:

int leds[] = {2, 3, 4};

Now, you can easily control all three LEDs using a single loop.


🔁 Example: Turning LEDs On and Off with an Array

Here’s how you can use arrays with loops to control multiple LEDs:

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

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

void loop() {
  for (int i = 0; i < 5; i++) {
    digitalWrite(leds[i], HIGH);
    delay(300);
    digitalWrite(leds[i], LOW);
  }
}

🟢 What’s happening:
Each LED lights up one by one using the array’s index.
It’s neat, clean, and super easy to scale up.


⚙️ Updating Array Values

You can also change array values during your program.

Example:

int sensorValues[3];

void loop() {
  for (int i = 0; i < 3; i++) {
    sensorValues[i] = analogRead(i);
    Serial.println(sensorValues[i]);
  }
  delay(1000);
}

Here, each element stores a sensor reading from pins A0–A2.


🧩 Quick Tips

✅ Arrays always start at index 0.
✅ The number inside the brackets [ ] tells you how many values it can hold.
✅ Always make sure you don’t go past the last index — it can crash your code.


🚀 In Summary

Arrays help you keep your Arduino code tidy and flexible.
They’re perfect when you have several similar inputs or outputs, like LEDs, sensors, or buttons.

Once you learn to use arrays, your sketches will be cleaner, faster, and easier to expand as your projects grow.