2

I would like to change the delay() into a nonblocking function in the code below. I've implemented it (a part of a tutorial from arduino.cc) in my code, but the delay() is blocking the rest of my code. Can anyone help me to change this?

void speelMelodie(int melodie){

if(melodie == 1){

      for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      tone(speaker, melody1[thisNote], noteDuration);

      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes); // <-- this one has to be changed

      noTone(speaker);
      }
  }

else if (melodie == 2) {
      // the same part as previous part (for loop)
  }


else if (melodie == 3) {
      // the same part as previous part (for loop)
  }
}
Joost
  • 75
  • 1
  • 1
  • 6

1 Answers1

1

Define global vars befor setup()

unsigned long timeStamp = 0; 
bool pauseOn = false;

and use it

void speelMelodie(int melodie) {

  if (melodie == 1) {

    for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      if (millis() - timeStamp < noteDuration && pauseOn == false) {
         tone(speaker, melody1[thisNote], noteDuration);
      } else { // reset value and change pauseOn to true
        pauseOn = true;
        timeStamp = millis();
      }
      int pauseBetweenNotes = noteDuration * 1.30;

      //delay(pauseBetweenNotes); // <-- this one has to be changed
      if (millis() - timeStamp < pauseBetweenNotes && pauseOn == true) {
          noTone(speaker);
      } else {
         pauseOn = false;
         timeStamp = millis();
      }
    }
  }
}

We need the state variable pauseOn to differentiate between the two states play note or silence. The code compiles, but you have to finetune in your program.
A final tip Tutorials using delay() other than

  • for debuging or
  • in setup for initializing hardware

are of very low quality
-> Its like a blind person talking about color composition.

Codebreaker007
  • 1,331
  • 1
  • 7
  • 14