Playing melodies with tone() in Arduino - Time & Space Complexity
When playing melodies with the tone() function, the time it takes depends on how many notes you play.
We want to know how the total time grows as the number of notes increases.
Analyze the time complexity of the following code snippet.
const int buzzer = 8;
int melody[] = {262, 294, 330, 349};
int noteDurations[] = {4, 4, 4, 4};
void playMelody() {
for (int i = 0; i < 4; i++) {
int duration = 1000 / noteDurations[i];
tone(buzzer, melody[i], duration);
delay(duration * 1.3);
}
}
This code plays a melody of 4 notes on a buzzer, each with a specific duration.
- Primary operation: The
forloop that plays each note one by one. - How many times: It runs once for each note in the melody array.
As you add more notes, the total time to play the melody grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 notes played, so 10 loop runs |
| 100 | 100 notes played, so 100 loop runs |
| 1000 | 1000 notes played, so 1000 loop runs |
Pattern observation: The time grows evenly as you add more notes.
Time Complexity: O(n)
This means the time to play the melody grows directly with the number of notes.
[X] Wrong: "Playing more notes doesn't take more time because the buzzer plays fast."
[OK] Correct: Each note takes a certain time to play, so more notes mean more total time.
Understanding how loops affect time helps you explain how programs handle repeated tasks, like playing sounds or processing data.
"What if we added a nested loop to play each note multiple times? How would the time complexity change?"
