// Define the digital pins connected to the relay modules (corresponding to note pitches A to J)
const int relay[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // Example pin numbers (adjust as needed)
// Define the sequence of notes and durations for "We Wish You a Merry Christmas"
String melody = "QG 1, QG 1, HF 1, EDb 0.5, EDb 0.5, EDb 0.5, HF 1, QG 1, QG 1, HF 1, EDb 0.5, EDb 0.5, EDb 0.5, HF 1, QG 1, QG 1, HF 2, QG 1, QG 1, HF 1, EDb 0.5, EDb 0.5, EDb 0.5, HF 1, QG 1, QG 1, HF 1, EDb 0.5, EDb 0.5, EDb 0.5, HF 1, QG 1, QG 1, HF 2";
void setup() {
// Set all relay pins as outputs
for (int i = 0; i < sizeof(relay) / sizeof(relay[0]); i++) {
pinMode(relay[i], OUTPUT);
}
}
void loop() {
int noteIndex = 0; // Index to track the current note in the melody
while (noteIndex < melody.length()) {
// Parse the current note and duration from the melody string
String currentNote = "";
while (melody.charAt(noteIndex) != ' ' && noteIndex < melody.length()) {
currentNote += melody.charAt(noteIndex);
noteIndex++;
}
noteIndex++; // Skip the space after the note
// Extract the note and duration from the parsed string
String noteType = currentNote.substring(0, 1); // Note type (e.g., Q, H, E)
String notePitch = currentNote.substring(1); // Note pitch (e.g., G, F, D#, etc.)
float noteDuration = currentNote.substring(2).toFloat(); // Note duration (e.g., 1, 0.5, 2, etc.)
// Activate the corresponding relay based on the note pitch
int relayIndex = notePitch.charAt(0) - 'A'; // Convert note pitch to relay index (A=0, B=1, C=2, etc.)
// Check if the relay index is within valid range
if (relayIndex >= 0 && relayIndex < sizeof(relay) / sizeof(relay[0])) {
// Activate the relay (assuming active LOW; check your relay module's specifications)
digitalWrite(relay[relayIndex], LOW); // Set the pin LOW to activate the relay
}
// Delay for the specified duration (converted to milliseconds)
delay(noteDuration * 1000); // Convert seconds to milliseconds
// Deactivate the relay after the note duration
if (relayIndex >= 0 && relayIndex < sizeof(relay) / sizeof(relay[0])) {
digitalWrite(relay[relayIndex], HIGH); // Set the pin HIGH to deactivate the relay
}
// Delay between notes (adjust as needed)
delay(10); // Small delay between notes
}
// Optionally add a longer delay before restarting the sequence
delay(20); // Wait for 2 seconds before restarting the sequence
Serial.println();
}