// Define the speaker pin
#define SPEAKER_PIN 4
// Define melodies as arrays of notes (frequencies in Hz)
int melody1[] = {262, 294, 330, 349, 392, 440, 494, 523}; // C major scale
int melody2[] = {523, 494, 440, 392, 349, 330, 294, 262}; // Descending C major scale
int melody3[] = {330, 349, 392, 440, 392, 349, 330, 294}; // Twinkle twinkle pattern
int melody4[] = {440, 440, 440, 349, 349, 349, 330, 330}; // Rhythm pattern
int melody5[] = {262, 330, 392, 440, 392, 330, 294, 262}; // Custom tune
// Define the duration for each note (in milliseconds)
int noteDuration = 500; // 500ms per note
// Function to play a melody
void playMelody(int melody[], int length, int duration, const char* melodyName) {
Serial.print("Playing melody: ");
Serial.println(melodyName);
unsigned long startTime = millis();
while (millis() - startTime < duration) {
for (int i = 0; i < length; i++) {
tone(SPEAKER_PIN, melody[i], noteDuration); // Play note
delay(noteDuration * 1.3); // Add a pause between notes
}
}
Serial.print("Finished playing: ");
Serial.println(melodyName);
}
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud
pinMode(SPEAKER_PIN, OUTPUT);
}
void loop() {
// Play each melody for 20 seconds
playMelody(melody1, sizeof(melody1) / sizeof(melody1[0]), 20000, "Melody 1 (C Major Scale)");
delay(1000); // Pause between tunes
playMelody(melody2, sizeof(melody2) / sizeof(melody2[0]), 20000, "Melody 2 (Descending C Major Scale)");
delay(1000);
playMelody(melody3, sizeof(melody3) / sizeof(melody3[0]), 20000, "Melody 3 (Twinkle Twinkle Pattern)");
delay(1000);
playMelody(melody4, sizeof(melody4) / sizeof(melody4[0]), 20000, "Melody 4 (Rhythm Pattern)");
delay(1000);
playMelody(melody5, sizeof(melody5) / sizeof(melody5[0]), 20000, "Melody 5 (Custom Tune)");
delay(1000);
// Repeat loop
}