Using millis() with tone() and pitches.h

As part of a larger project, I am incorporating a short tone() melody to serve as background music to a small game using an 8x8 LED matrix. In order to drive the LED quickly enough, I needed to remove delay()'s from all code, and transition to millis() timing. In doing so though, the tune I pecked out on the default Tone tutorial code now sounds much distorted. I have fiddled with the noteDuration math, as well as the pauseBetweenNote durations, but it does not seem to relate to that.

I do not know enough about producing tones through electronics to guess at a fix. Any guidance would be tremendous!

 #include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_E1, NOTE_F2, NOTE_F3, NOTE_E1, NOTE_F2, NOTE_F3, NOTE_E1, NOTE_F2, // 1
  NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, // 2
  NOTE_C1, NOTE_F1, NOTE_F2, NOTE_C1, NOTE_F1, NOTE_F2, NOTE_C1, NOTE_F1, // 3
  NOTE_C1, NOTE_F1, NOTE_F2, NOTE_C1, NOTE_F1, NOTE_F2, NOTE_C1, NOTE_F1, // 4
  NOTE_E1, NOTE_F2, NOTE_F3, NOTE_E1, NOTE_F2, NOTE_F3, NOTE_E1, NOTE_F2, // 5
  NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, // 6
  NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, // 7
  NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, // 8
  NOTE_E1, NOTE_F2, NOTE_F3, NOTE_E1, NOTE_F2, NOTE_F3, NOTE_E1, NOTE_F2, // 9
  NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, NOTE_F2, NOTE_D1, NOTE_F1, // 10
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 4, 4, 4, 4, 4, 4, 4, // 1
  4, 4, 4, 4, 4, 4, 4, 4, // 2
  4, 4, 4, 4, 4, 4, 4, 4, // 3
  4, 4, 4, 4, 4, 4, 4, 4, // 4
  4, 4, 4, 4, 4, 4, 4, 4, // 5
  4, 4, 4, 4, 4, 4, 4, 4, // 6
  4, 4, 4, 4, 4, 4, 4, 4, // 7
  4, 4, 4, 4, 4, 4, 4, 4, // 8
  4, 4, 4, 4, 4, 4, 4, 4, // 9
  4, 4, 4, 4, 4, 4, 4, 4, // 10
 };

void setup() { 
}

void loop() {

    for (int thisNote = 0; thisNote < 80; thisNote++) {
   
    unsigned long currentMillis = millis();
    
    int noteDuration = 1000/noteDurations[thisNote];
    int pauseBetweenNotes = noteDuration * 1.3;

    if(currentMillis - previousMillis > pauseBetweenNotes) {
      tone(3, melody[thisNote],noteDuration);
      previousMillis = currentMillis;
    } 
  } 
}

Tone_sans_delays.ino (2.26 KB)