1

I'd like to write a code by changing the delay function in the music playing code to the millis function, do you know how?

#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; thisNote++) {

    // to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(8);
  }
}

void loop() {
  // no need to repeat the melody.
}
6
  • 2
    Have you looked and understood the BlinkWithoutDelay example, that comes with the Arduino IDE? Have you tried some of the many tutorials about millis(), that are available on the web? If yes, what exactly are your problems in changing the code accordingly?
    – chrisl
    Oct 5, 2020 at 8:00
  • 1
    Does this answer your question? Playing Melody with Tone() without using delay()
    – Juraj
    Oct 5, 2020 at 8:13
  • Why do you want to get rid of the delay()? Your tone() call delays (blocks while playing) as well... Oct 5, 2020 at 13:57
  • @DataFiddler, it is one of the basic examples in IDE, not a code by OP
    – Juraj
    Oct 5, 2020 at 14:14
  • 1
    I still consider my question "why?" valid. If you use blocking tone() calls, creating the "pizzicato" effect via a small delay() is straightforward. The call noTone(8);is wrong (=unnecessary) here, BTW. @chrisl's hint regarding BlinkWithoutDelay is good, if you change to non-blocking tone() creation as well. And if you need other things faster than a tone duration. Oct 6, 2020 at 11:32

0

Browse other questions tagged or ask your own question.