// Arduino Buzzer Music Loop
// Connect buzzer positive to pin 8, negative to GND
const int buzzerPin = 8;
// Note frequencies (in Hz)
#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
#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_G5 784
#define REST 0
int melody[] = {
262, 330, 392, 523, 659, 784, 523, 392,
440, 523, 659, 440, 523, 330, 440, 330,
349, 440, 523, 698, 440, 523, 349, 523,
392, 492, 587, 784, 587, 492, 392, 262,
262, 392, 262, 392, 330, 492, 330, 492,
262, 330, 392, 523, 659, 784, 659, 523
};
int noteDurations[] = {
150, 150, 150, 150, 150, 150, 150, 150,
150, 150, 150, 150, 150, 150, 150, 150,
140, 140, 140, 140, 140, 140, 140, 140,
140, 140, 140, 140, 140, 140, 140, 140,
130, 130, 130, 130, 130, 130, 130, 130,
120, 120, 120, 120, 120, 120, 150, 150
};
void setup() {
pinMode(buzzerPin, OUTPUT);
Serial.begin(9600);
Serial.println("Playing music!");
}
void loop() {
playMelody();
//delay(100);
}
void playMelody() {
int totalNotes = sizeof(melody) / sizeof(melody[0]);
Serial.print("Playing melody with ");
Serial.print(totalNotes);
Serial.println(" notes...");
for (int i = 0; i < totalNotes; i++) {
if (melody[i] == REST) {
// Rest - no tone
noTone(buzzerPin);
} else {
// Play the note
tone(buzzerPin, melody[i]);
}
// Hold the note for its duration
delay(/*noteDurations[i]*/150);
// Small pause between notes
noTone(buzzerPin);
delay(50);
}
Serial.println("Melody complete!");
}