// Define the speaker pin
#define SPEAKER_PIN 4
// Define LED pins
int ledPins[] = {5, 6, 7, 8,9,10,11,12}; // Seven LEDs connected to pins 2-8
int numLeds = sizeof(ledPins) / sizeof(ledPins[0]);
// 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 chase LEDs back and forth
void chaseLeds(int delayTime) {
// Forward direction
for (int i = 0; i < numLeds; i++) {
digitalWrite(ledPins[i], HIGH);
delay(delayTime);
digitalWrite(ledPins[i], LOW);
}
// Reverse direction
for (int i = numLeds - 2; i >= 0; i--) {
digitalWrite(ledPins[i], HIGH);
delay(delayTime);
digitalWrite(ledPins[i], LOW);
}
}
// 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
chaseLeds(100); // Chase LEDs
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
// Initialize speaker pin
pinMode(SPEAKER_PIN, OUTPUT);
// Initialize LED pins
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW);
}
}
void loop() {
// Play each melody for 20 seconds
playMelody(melody1, sizeof(melody1) / sizeof(melody1[0]), 20000, "Melody 1 (C Major Scale)");
delay(10); // Pause between tunes
playMelody(melody2, sizeof(melody2) / sizeof(melody2[0]), 20000, "Melody 2 (Descending C Major Scale)");
delay(10);
playMelody(melody3, sizeof(melody3) / sizeof(melody3[0]), 20000, "Melody 3 (Twinkle Twinkle Pattern)");
delay(10);
playMelody(melody4, sizeof(melody4) / sizeof(melody4[0]), 20000, "Melody 4 (Rhythm Pattern)");
delay(10);
playMelody(melody5, sizeof(melody5) / sizeof(melody5[0]), 20000, "Melody 5 (Custom Tune)");
delay(10);
// Repeat loop
}