0

I've followed the directions from this answer, to try and play music without delay. This is my code so far:

#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

const int tonePin = 4;
unsigned long previousMillis = 0;
int counter = 0;
int numberOfNotes = sizeof(melody)/sizeof(int);
boolean outputTone = false;

void setup() {
  pinMode(tonePin, OUTPUT); 
  //Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();
  unsigned long noteDuration = 1000 / noteDurations[counter];
  unsigned long pauseBetweenNotes = noteDuration * 1.30;


  if (counter < numberOfNotes) {
    if (outputTone && ((currentMillis - previousMillis) >= noteDuration)) {
        previousMillis = currentMillis;
        noTone(tonePin);
        outputTone = false;
        counter++;
    }
    else {
        if ((currentMillis - previousMillis) >= pauseBetweenNotes) {
        previousMillis = currentMillis;
        Serial.println(melody[counter]);

        if (melody[counter] == 0) {
          noTone(tonePin);
        } else {
          tone(tonePin, melody[counter]);
        }

        outputTone = true;
      }
    }
  }
}

pitches.h can be found here.

So with this code, the music plays, but slower. The pauses between notes seem longer, and I can't figure out why.

Also, I'm not sure where should I increment my notes counter.

0

In this code, your pauseBetweenNotes is *in addition to * the duration of the note. In your previous code, IIRC, it included the duration of the note.

Change it to 0.3 times and I think it will behave as you expect.

  • This is the example. If I understand correctly, a note is played for the duration of noteDuration, and then there is a silence for pauseBetweenNotes, and so on, and that, noteDuration + pauseBetweenNotes is the full duration of one note? But pauseBetweenNotes is still a full note duration + 30%? (There is no need for the noTone function then right?). – kok_nikol Feb 13 '17 at 18:50
  • I've never used this pitches library, but it looks like tone() returns immediately, and the note carries on playing in the background. In the linked example, the tone will start playing and the code will continue. It immediately sleeps for 1.3x the length of the note - so the note will finish and then we'll still have 0.3x the length to sleep. Does that make sense? In your code above, we wait for the length of the note, and THEN sleep for 1.3x the length of the note. – Mark Smith Feb 13 '17 at 21:34
0

There's a variable called "pauseBetweenNotes". Try modifying that and see if the pause between notes becomes smaller.

Regarding your counter question, the way the counter is set up looks fine to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.