I want to make a buzzer play one of two tunes according to the button I press. So far, the first song plays immediately without pressing any buttons and then it only works for one side, with the song playing till the end ignoring all button presses.
Here is my code:
#include "pitches.h"
// notes in the melody:
int melody1[] = {
NOTE_E5, NOTE_DS5, NOTE_E5, NOTE_DS5, NOTE_E5, NOTE_B4, NOTE_D5, NOTE_C5, NOTE_A4, 0, NOTE_C4, NOTE_E4, NOTE_A4, NOTE_B4, 0,
NOTE_E4, NOTE_GS4, NOTE_B4, NOTE_C5, 0, NOTE_E4, NOTE_E5, NOTE_DS5, NOTE_E5, NOTE_DS5, NOTE_E5, NOTE_B4, NOTE_D5, NOTE_C5,
NOTE_A4, 0, NOTE_C4, NOTE_E4, NOTE_A4, NOTE_B4, 0, NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4
};
int melody2[] = {
NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_C5, NOTE_E4, NOTE_C5, NOTE_E4, NOTE_C5, 0, NOTE_C5, NOTE_D5, NOTE_DS5, NOTE_E5, NOTE_C5, NOTE_D5,
NOTE_E5, NOTE_B4, NOTE_D5, NOTE_C5, 0, NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_C5, NOTE_E4, NOTE_C5, NOTE_E4, NOTE_C5, 0, NOTE_A4, NOTE_G4,
NOTE_FS4, NOTE_A4, NOTE_C5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_D5, 0, NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_C5, NOTE_E4, NOTE_C5,
NOTE_E4, NOTE_C5, 0, NOTE_C5, NOTE_D5, NOTE_DS5, NOTE_E5, NOTE_C5, NOTE_D5, NOTE_E5, NOTE_B4, NOTE_D5, NOTE_C5
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int notedurations1[] = {
8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 4, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 4, 8, 8, 8, 8, 2
};
int notedurations2[] = {
8, 8, 8, 4, 8, 4, 8, 3, 4, 8, 8, 8, 8, 8, 8, 4, 8, 4, 3, 4, 8, 8, 8, 4, 8, 4, 8, 2, 4, 8, 8, 8, 8, 8, 4, 8, 8, 8, 3, 4, 8, 8, 8, 4, 8,
4, 8, 3, 4, 8, 8, 8, 8, 8, 8, 4, 8, 4, 3, 4,
};
const int button1 = 2;
const int button2 = 3;
const int piezo = 8;
int buttonState1 = 0;
int buttonState2 = 0;
void setup() {
// iterate over the notes of the melody:
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
pinMode(piezo, OUTPUT);
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
}
void playSong(int OutputPin, int Melody[], int NoteDurations[], int NumberOfNotes){
for (int thisNote = 0; thisNote < NumberOfNotes; thisNote++) {
int NoteDuration = 1000 / NoteDurations[thisNote];
tone(OutputPin, Melody[thisNote], NoteDuration);
int pauseBetweenNotes = NoteDuration * 1.30;
delay(pauseBetweenNotes);
}
noTone(OutputPin);
}
void loop() {
buttonState1 = digitalRead(button1);
buttonState2 = digitalRead(button2);
if (buttonState1 == HIGH && buttonState2 == LOW) {
playSong(8, melody1, notedurations1, sizeof(melody1)/sizeof(melody1[0]));
}
else if (buttonState1 == LOW && buttonState2 == HIGH) {
playSong(8, melody2, notedurations2, sizeof(melody2)/sizeof(melody2[0]));
}
else { }
// stop the tone playing:
}
I have posted about this before but no one responded to my recent update about a week ago so I decided to post it again.
Thanks!