Hi. I want to preface this by letting you know that I am a novice at this, so please be patient with me.
I have been working on a program to make two piezo elements play music together. I have used the millis() function to make the two rapidly loop to give the illusion that they are playing simultaneously. I have made that part work, but I am unable to figure out how to make a short pause in between the music notes so they can be heard. My comments in the code show where the pause needs to be.
#include "pitches.h"
#define pz1 8
#define pz2 9
unsigned long previousMillis = 0; //some global variables available anywhere in the program
unsigned long currentMillis;
unsigned long startMillis;
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 mnoteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
int bass[] = {
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 bnoteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void taskMelody () {
static unsigned long chrono = millis();
if (currentMillis - chrono < 5000) return;
chrono = millis();
// iterate over the notes of the melody:
for (int mthisNote = 0; mthisNote < 8; mthisNote++) {
int mnoteDuration = 1000 / mnoteDurations[mthisNote];
int mpauseBetweenNotes = mnoteDuration * 1.30;
tone(pz1, melody[mthisNote], mnoteDuration);
//I need to make a pause here equal to mpauseBetweenNotes
noTone(pz1);
}
}
void taskBass (/* put arguments here */) {
static unsigned long chrono = millis();
if (millis() - chrono < 5000) return;
chrono = millis();
for (int bthisNote = 0; bthisNote < 8; bthisNote++) {
int bnoteDuration = 1000 / bnoteDurations[bthisNote];
tone(pz2, bass[bthisNote], bnoteDuration);
int bpauseBetweenNotes = bnoteDuration * 1.30;
//I need to make a pause here equal to bpauseBetweenNotes
noTone(pz2);
}
}
void setup(){
startMillis = millis(); //initial start time
}
void loop () {
currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started)
taskMelody (/* arguments for task 1 */);
taskBass (/* arguments for task 2 */);
}