Hi.
(Please see the full code in the attachment, unable to paste full code directly, goes beyond posting limit).
In the following version of the code, all was well. Even though there was a minor delay, the return function worked as intended and pressing the alarm button while the melody was playing, did switch off the alarm.
void playTone(int tone, int duration)
{
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
void playNote(char note, int duration)
{
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
// play the tones according to the notes
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
void playAlarm()
{
if ((secondClock == secondAlarm && minuteClock == minuteAlarm && hourClock == hourAlarm && alarmOnOff == true))
{
for (int i = 0; i < length; i++)
{
playNote(notes[i], beats[i] * tempo);
delay(tempo / 4);
//read the alarm button value, if the "mode change" button is pressed while alarm is playing, it will take the system to alarm mode and switch alarm off.
alarmValue = analogRead(buttonAlarm);
if (alarmValue < 1000)
{
alarmOnOff = false;
return;
}
}
}
return;
}
//main loop to recall all functions
void loop()
{
timing();
lightOnLed(modeClock);
readButtons();
playAlarm();
}
But that was not exactly the melody that I wanted. So, I found another one. But this other one is in a different format. Although, I tried to make it fit with the code that I have, I noticed the return; function is no longer working, because if I press the alarm button while the tone is playing, it does nothing. it is supposed to switch alarm off.
New version of code: (ofcourse, there is more notes to it, than I have pasted, but this is only for the sake of demonstration.
void playAlarm()
{
if ((secondClock == secondAlarm && minuteClock == minuteAlarm && hourClock == hourAlarm && alarmOnOff == true))
{
// Set this to be the pin that your buzzer resides in. (Note that you can only have one buzzer actively using the PWM signal at a time).
int tonePin = 9;
tone(tonePin, 523, 562.5);
delay(625.0);
delay(312.5);
tone(tonePin, 391, 281.25);
delay(312.5);
tone(tonePin, 523, 562.5);
delay(625.0);
tone(tonePin, 391, 421.875);
delay(468.75);
//read the alarm button value, if the "mode change" button is pressed while alarm is playing, it will take the system to alarm mode and switch alarm off.
alarmValue = analogRead(buttonAlarm);
if (alarmValue < 1000)
{
alarmOnOff = false;
return;
}
}
return;
}
//main loop to recall all functions
void loop()
{
timing();
lightOnLed(modeClock);
readButtons();
playAlarm();
}