// Pin for the buzzer
const int buzzerPin = 9;
// Frequencies of the notes (in Hertz)
#define NOTE_C4 261
#define NOTE_D4 294
#define NOTE_E4 329
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
// Melody of "Twinkle, Twinkle, Little Star"
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
};
// Durations of each note (in ms)
int noteDurations[] = {
400, 400, 400, 400,
400, 400, 400, 400,
400, 400, 400, 400,
400, 400
};
void setup() {
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// Play each note in the melody
for (int thisNote = 0; thisNote < 14; thisNote++) {
int noteDuration = noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
// Wait for the note to finish playing
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(buzzerPin);
}
// Wait before repeating the melody
delay(2000);
}