Hey everyone,
I'm working on a project where I'm trying to play the Imperial March theme on a piezo buzzer using Arduino, but it's not working out as planned. I thought I followed all the steps correctly, but when I run my project, I don't hear the music. I think there might be an issue with my code or maybe how I've set up everything on the breadboard.
I'd really appreciate it if someone could take a look at my code and wiring to see if you can spot any mistakes. Here's my code:
const int buzzerPinMelody = 8; // Active Buzzer for Melody
const int buzzerPinHarmony = 9; // Passive Buzzer for Harmony
// Melody of the Imperial March
int melody[] = {
440, 440, 440, 349, 523, 440, 349, 523, 440, 0,
659, 659, 659, 698, 523, 415, 349, 523, 440, 0,
880, 880, 880, 349, 523, 440, 349, 523, 440, 0,
659, 659, 659, 698, 523, 415, 349, 523, 440, 0
};
// Durations for each note in the melody
int melodyDurations[] = {
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500,
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500,
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500,
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500
};
// Harmony for the Imperial March (simplified example)
int harmony[] = {
349, 349, 349, 294, 466, 349, 294, 466, 349, 0,
622, 622, 622, 659, 466, 392, 294, 466, 349, 0,
784, 784, 784, 294, 466, 349, 294, 466, 349, 0,
622, 622, 622, 659, 466, 392, 294, 466, 349, 0
};
// Durations for each note in the harmony
int harmonyDurations[] = {
// Ensure these match the melody durations or are adjusted according to your harmony timing
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500,
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500,
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500,
500, 500, 500, 350, 150, 500, 350, 150, 1000, 500
};
unsigned long previousMillis = 0;
int noteIndex = 0;
bool notePlaying = false;
void setup() {
pinMode(buzzerPinMelody, OUTPUT);
pinMode(buzzerPinHarmony, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (noteIndex < sizeof(melody) / sizeof(melody[0])) { // Ensure within array bounds
if (!notePlaying) {
// Start playing a new note
tone(buzzerPinMelody, melody[noteIndex]);
tone(buzzerPinHarmony, harmony[noteIndex]);
previousMillis = currentMillis;
notePlaying = true;
} else if (currentMillis - previousMillis >= melodyDurations[noteIndex]) {
// Note duration has passed
noTone(buzzerPinMelody);
noTone(buzzerPinHarmony);
notePlaying = false;
noteIndex++;
// Add a brief pause between notes
previousMillis = currentMillis + 50; // Adjust this value to control the pause duration
}
} else if (currentMillis - previousMillis >= 2000 && !notePlaying) { // Wait before restarting
noteIndex = 0; // Restart the melody and harmony
}
}
And here's how I've set up my breadboard (but I'm not sure if everything's connected right):
So, if anyone can give me advice on what I'm doing wrong or how to fix it, that would be awesome. Thanks a lot!
Warm regards,
3konverts.