I want my arduino to play a melody without using the delay() function (multitasking). this is the code I have so far:
int tempo = 200;
int buzzer = 13;
int melody[]={
NOTE_E5,8, NOTE_E5,8, REST,8, NOTE_E5,8, REST,8, NOTE_C5,8, NOTE_E5,8, //1
NOTE_G5,4, REST,4, NOTE_G4,8, REST,4,
NOTE_C5,-4, NOTE_G4,8, REST,4, NOTE_E4,-4, // 3
NOTE_A4,4, NOTE_B4,4, NOTE_AS4,8, NOTE_A4,4,
NOTE_G4,-8, NOTE_E5,-8, NOTE_G5,-8, NOTE_A5,4, NOTE_F5,8, NOTE_G5,8,
REST,8, NOTE_E5,4,NOTE_C5,8, NOTE_D5,8, NOTE_B4,-4,
NOTE_C5,-4, NOTE_G4,8, REST,4, NOTE_E4,-4, // repeats from 3
NOTE_A4,4, NOTE_B4,4, NOTE_AS4,8, NOTE_A4,4,
NOTE_G4,-8, NOTE_E5,-8, NOTE_G5,-8, NOTE_A5,4, NOTE_F5,8, NOTE_G5,8,
REST,8, NOTE_E5,4,NOTE_C5,8, NOTE_D5,8, NOTE_B4,-4,
};
int notes = sizeof(lied1) / sizeof(lied1[0]) / 2;
// this calculates the duration of a whole note in ms
int wholenote = (60000 * 4) / tempo;
int divider = 0, noteDuration = 0;
boolean outputTone = false;
unsigned long previousMillis = millis();
int thisNote = 0;
while (thisNote < notes * 2) {
// calculates the duration of each note
divider = lied1[thisNote + 1];
if (divider > 0) {
// regular note, just proceed
noteDuration = (wholenote) / divider;
} else if (divider < 0) {
// dotted notes are represented with negative durations!!
noteDuration = (wholenote) / abs(divider);
noteDuration *= 1.5; // increases the duration in half for dotted notes
}
if (millis() - previousMillis >= noteDuration) {
previousMillis = millis();
if (outputTone) {
noTone(buzzer);
outputTone==false;
} else {
tone(buzzer, melody[thisNote], noteDuration*0.9);
outputTone==true;
thisNote = thisNote + 2;
}
}
}
It does not work, the first notes do, but the other notes do not work properly.