Section outline

  • Arrays – Handling Multiple Values Smartly

    As your projects grow, you might want to manage multiple values — like storing the readings from 3 sensors or controlling 4 LEDs. Instead of creating separate variables for each one, you can use an array.

    • 📦 What is an Array?

      An array is like a container that holds multiple values of the same type (like integers or floats), all under one name. Each item is stored at an index (starting from 0).

      Example: Store 4 LED pin numbers
      int ledPins[] = {3, 5, 6, 9};

      You can now access each LED pin using its index, like ledPins[0] or ledPins[3].

      💡 Using Arrays in a Loop

      This is where arrays really shine! Combine arrays with for loops to control many pins easily.

      Example: Turn ON all LEDs one by one
      int ledPins[] = {3, 5, 6, 9};
      
      void setup() {
        for (int i = 0; i < 4; i++) {
          pinMode(ledPins[i], OUTPUT);
        }
      }
      
      void loop() {
        for (int i = 0; i < 4; i++) {
          digitalWrite(ledPins[i], HIGH);
          delay(300);
          digitalWrite(ledPins[i], LOW);
          delay(300);
        }
      }
    • 🔍 When to Use Arrays?

      • When you have multiple sensors or outputs that behave similarly.
      • When you want to store multiple readings or values together.
      • When writing repeated logic with minimal code.

      ⚠️ Array Tips

      • Always start counting from index 0.
      • Make sure you don’t access an index outside the array size — it may cause bugs!
      • You can create arrays for int, float, char, and even custom data types.

      Now that you’ve learned how to group and use multiple values, let’s take it further and bring in some ready-made tools with libraries in the next section.