Introduction: How to Make a Melody With Arduino & a Speaker With GPT Code
How to Make a Melody with Arduino & a Speaker 🎶
Want to make your Arduino sing? It’s easy — with an Arduino, a speaker (or piezo buzzer), and a few lines of code you can play melodies, alarms, chimes or game sounds. This post shows wiring, the code, and explanations so beginners can follow step-by-step.
more information watch this video https://youtube.com/shorts/ixvUWjSg7Ic?feature=share
Supplies
Parts you need
- Arduino Uno (or Nano / any Arduino)
- Piezo buzzer (passive) or small 8Ω speaker + transistor if using a speaker
- 1 × 220Ω resistor (optional for speaker)
- Jumper wires
- Breadboard (optional)
- USB cable for programming
Attachments
Step 1:
Arduino generates a square wave on a digital pin at the frequency of the desired note. The piezo/speaker converts these electrical oscillations into pressure waves — sound. The Arduino tone() function makes this straightforward by producing the correct frequency for each musical note.
// Melody example for Arduino + piezo/speaker
const int speakerPin = 8;
// Notes in Hz for common notes
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
// Twinkle Twinkle melody (notes) and durations
int melody[] = {
NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4,
NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4
};
int noteDurations[] = {
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2
};
void setup() {
// nothing required here for tone()
}
void loop() {
int notes = sizeof(melody) / sizeof(melody[0]);
for (int thisNote = 0; thisNote < notes; thisNote++) {
int duration = 1000 / noteDurations[thisNote]; // duration in ms
tone(speakerPin, melody[thisNote], duration);
// pause between notes, 30% longer than note's duration
int pauseBetween = duration * 1.30;
delay(pauseBetween);
noTone(speakerPin); // stop the tone
}
delay(1000); // wait before repeating
}
If the sound is too quiet with a speaker, use a transistor driver and an external supply (keep grounds common).
If you hear clicks between notes, shorten the delay() after noTone() or fine-tune the pause multiplier.
Use passive piezo for melodies (active buzzers only produce fixed beeps).
For longer or more complex songs, store note arrays in PROGMEM to save RAM.
To change tempo, multiply durations by a tempo factor.
Use PWM pins and analogWrite() to create softer tones (but tone() is simpler).
Use buttons to play different songs or change tempo.
Combine with LEDs for a light-and-sound effect.






