Lesson 9.5: Arrays and Data Structures

Organizing collections of values so your programs can handle patterns, melodies, and poses

🧩 This supplemental lesson prepares you for Lesson 10, where melodies and motion patterns are stored as arrays and structs.

🤔 Why This Lesson Exists

In Lesson 10, we play melodies and run motion patterns. A melody is not one number — it is a list of notes played in order. A robot arm pose is not one number either — it is a group of angles that belong together (base, elbow, shoulder, gripper).

C++ gives us two tools for this: arrays (lists of the same type of value) and structs (groups of related values that belong to one "thing"). This lesson shows you both with small examples you can run on the same hardware you already have wired up.

🎯 Learning Objectives

By the end of this lesson, you will:

  • • Declare and use arrays to store lists of values
  • • Loop through arrays with for loops
  • • Use parallel arrays for related data (note + duration)
  • • Group related fields with struct

Key Concepts:

  • • Zero-based indexing (myArray[0] is the first item)
  • • sizeof() to find array length safely
  • • Arrays of structs for patterns and poses
  • • How this connects to Lesson 10's melodies and the robot arm

📝 Section 1: The Problem Arrays Solve

Imagine storing a 5-note melody using only single variables:

// Without arrays - painful and repetitive!
int note1 = 262;
int note2 = 294;
int note3 = 330;
int note4 = 349;
int note5 = 392;

// To play them you would copy/paste tone() five times...
// What if the melody had 50 notes?

An array stores many values under one name. Each value gets an index (its position number), starting at 0:

// With an array - one name, many values
int notes[] = {262, 294, 330, 349, 392};

// notes[0] is 262 (first item)
// notes[4] is 392 (fifth item - index counts from 0!)

⚠️ Indexing gotcha: an array of 5 items has indexes 0 through 4. Asking for notes[5] reads memory outside the array — a classic bug source.

🔁 Section 2: Looping Through Arrays

Arrays shine when combined with a for loop — the loop counter i becomes the index. Use sizeof(array) / sizeof(array[0]) to get the number of items automatically:

// Array Basics - read and print every item
int notes[] = {262, 294, 330, 349, 392};

void setup() {
  Serial.begin(9600);
  
  int count = sizeof(notes) / sizeof(notes[0]);  // = 5
  
  for (int i = 0; i < count; i++) {
    Serial.print("notes[");
    Serial.print(i);
    Serial.print("] = ");
    Serial.println(notes[i]);
  }
}

void loop() {
  // nothing needed here
}

Why sizeof? If you later add a 6th note, the loop still works — you never have to update a hard-coded "5" somewhere else in the code. This is a habit worth building now.

🎵 Section 3: Parallel Arrays (Notes + Durations)

A melody needs two facts per note: the frequency and the duration. The simplest approach is two arrays kept in the same order — melody[i] pairs with noteDurations[i]. This is exactly what Lesson 10's melody code does (buzzer on pin 8):

// Parallel Arrays Mini-Melody (buzzer on pin 8)
const int buzzerPin = 8;

int melody[]        = {262, 330, 392, 523};  // C4, E4, G4, C5
int noteDurations[] = {4,   4,   4,   2};    // 4 = quarter note, 2 = half note

void setup() {
  int count = sizeof(melody) / sizeof(melody[0]);
  
  for (int i = 0; i < count; i++) {
    int duration = 1000 / noteDurations[i];
    tone(buzzerPin, melody[i], duration);
    delay(duration * 1.3);  // small gap between notes
    noTone(buzzerPin);
  }
}

void loop() {
  // Played once in setup()
}

💡 Parallel arrays work, but they have a weakness: the pairing lives only in your head. If the two lists get out of order, the song is wrong. Structs (next section) fix that by keeping each note's data together.

📦 Section 4: Structs — Grouping Related Data

A struct bundles several fields into one named type. Think of one "note" as a package containing a frequency and a duration. For our robot arm, a "pose" will package several servo angles.

// Struct Basics - one package holding related fields
struct Note {
  int frequency;   // Hz
  int duration;    // milliseconds
};

// Create two Note "packages"
Note noteA = {262, 500};   // C4 for half a second
Note noteB = {392, 250};   // G4 for a quarter second

void setup() {
  Serial.begin(9600);
  
  // Access fields with the dot operator
  Serial.print("noteA frequency: ");
  Serial.println(noteA.frequency);
  Serial.print("noteB duration: ");
  Serial.println(noteB.duration);
}

void loop() {
}

Arrays of Structs — the Best of Both

Combine them: an array of structs gives you a list where every item is a complete package. This is the exact pattern Lesson 10 uses for its audio-motion sequences:

// Array of Structs - a list of complete packages
struct Step {
  int servoPos;    // degrees (for pin 9 servo)
  int frequency;   // Hz (for pin 8 buzzer)
  int duration;    // ms
};

Step pattern[] = {
  {0,   262, 400},   // step 0: left + low note
  {90,  330, 400},   // step 1: center + mid note
  {180, 392, 400},   // step 2: right + high note
};

void setup() {
  Serial.begin(9600);
  
  int count = sizeof(pattern) / sizeof(pattern[0]);
  for (int i = 0; i < count; i++) {
    Serial.print("Step ");
    Serial.print(i);
    Serial.print(": servo=");
    Serial.print(pattern[i].servoPos);
    Serial.print(" deg, freq=");
    Serial.print(pattern[i].frequency);
    Serial.println(" Hz");
  }
}

void loop() {
}

🛠️ Hands-On: Preset Pose Sequencer

Use your standard wiring (servo on pin 9, buzzer on pin 8, button on A2). Each button press advances to the next pose in an array of structs — this is the same machinery that will drive "preset poses" on the robot arm:

// Preset Pose Sequencer
// Servo -> pin 9, Buzzer -> pin 8, Button -> A2 (to GND, INPUT_PULLUP)
#include <Servo.h>

Servo joint;
const int servoPin = 9;
const int buzzerPin = 8;
const int buttonPin = A2;

// Each pose = one package of related values
struct Pose {
  int angle;
  int beepFreq;
};

Pose poses[] = {
  {30,  262},    // C4
  {60,  294},    // D4
  {90,  330},    // E4
  {120, 392},    // G4
  {150, 523}     // C5
};

int poseIndex = 0;
int poseCount = sizeof(poses) / sizeof(poses[0]);
int lastButton = HIGH;

void setup() {
  joint.attach(servoPin);
  pinMode(buzzerPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
  
  // Start at first pose
  joint.write(poses[0].angle);
  Serial.println("Press button to step through poses");
}

void loop() {
  // read -> decide -> act
  int button = digitalRead(buttonPin);
  
  if (lastButton == HIGH && button == LOW) {
    poseIndex = poseIndex + 1;
    if (poseIndex >= poseCount) {
      poseIndex = 0;  // wrap around to the start
    }
    
    joint.write(poses[poseIndex].angle);
    tone(buzzerPin, poses[poseIndex].beepFreq, 150);
    
    Serial.print("Pose ");
    Serial.print(poseIndex);
    Serial.print(" -> angle ");
    Serial.println(poses[poseIndex].angle);
  }
  
  lastButton = button;
}

Try these extensions:

  • • Add a holdTime field to Pose and delay that long at each pose
  • • Use the potentiometer (A0) to choose which pose index to jump to
  • • Make a second array of poses and let the button toggle between arrays

📝 Quick Check

  1. If an array is declared as int data[] = 20;, what is data[2]?
  2. Why does sizeof(notes) / sizeof(notes[0]) give the number of items?
  3. What is the weakness of parallel arrays that a struct fixes?
  4. Write a struct called ArmPose with fields for a base angle and an elbow angle.

Where this goes next

Lesson 10 uses parallel arrays for melodies (melody[] + noteDurations[]) and an array of structs (struct Pattern) for coordinated sound + servo patterns. Later, the robot arm's "preset poses" (home, ready, reach) will be arrays of structs exactly like the activity above — but with one angle per joint.

← Previous: Lesson 9
Course Overview
Next: Lesson 10 →