Bird
0
0
Arduinoprogramming~30 mins

Playing melodies with tone() in Arduino - Mini Project: Build & Apply

Choose your learning style9 modes available
Playing melodies with tone()
📖 Scenario: You have a small buzzer connected to your Arduino. You want to play a simple melody by making the buzzer beep at different notes.
🎯 Goal: Build a program that plays a short melody using the tone() function on a buzzer connected to pin 8.
📋 What You'll Learn
Create an array called notes with the frequencies of the melody notes
Create an array called durations with the length of each note in milliseconds
Use a for loop with variable i to play each note using tone()
Use noTone() to stop the buzzer between notes
Print "Melody finished!" after playing all notes
💡 Why This Matters
🌍 Real World
Playing melodies with a buzzer is common in alarms, toys, and simple music projects.
💼 Career
Understanding how to control hardware like buzzers with code is useful for embedded systems and electronics jobs.
Progress0 / 4 steps
1
Set up the melody notes
Create an integer array called notes with these exact frequencies: 262, 294, 330, 349, 392.
Arduino
Hint

Use int notes[] = { ... }; to create the array with the exact frequencies.

2
Set up the note durations
Create an integer array called durations with these exact values: 500, 500, 500, 500, 500.
Arduino
Hint

Use int durations[] = { ... }; to create the array with the exact durations.

3
Play the melody using tone()
Write a for loop with variable i from 0 to 4 to play each note on pin 8 using tone(8, notes[i], durations[i]). After each note, add a delay of durations[i] plus 50 milliseconds. Then call noTone(8) to stop the buzzer.
Arduino
Hint

Use a for loop from 0 to 4. Inside, call tone(8, notes[i], durations[i]), then delay(durations[i] + 50), then noTone(8).

4
Print a message after the melody
Add a Serial.begin(9600) in setup() before the loop. After the for loop, add Serial.println("Melody finished!") to print the message.
Arduino
Hint

Call Serial.begin(9600) at the start of setup(). After the loop, call Serial.println("Melody finished!").