Hey guys, so I've been trying to write a song on arduino using a piezo buzzer. I successfully wrote the song for 1 piezo but I've been trying to have another piezo buzzer play at the same time with a different melody. I tried a bunch of things but still can't do it. I need a different melody and duration for the second piezo. Both need to be playing simultaneously. Any help is appreciated. Thank you!! I've post my code below.
//////////////////////////////////////////
#include "pitches.h"
const int piezoPin = 12; //piezo
const int piezoPin2 = 10; //piezo for second sound
const int pPin = 2; //pushbutton
int ledState = 0;
int ledOn = false;
// notes
int melody[] = {
NOTE_E5, NOTE_G5, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_B4, NOTE_C5, NOTE_G4,
NOTE_A4, NOTE_C5, NOTE_C5, NOTE_B4,
//chorus
NOTE_E5, NOTE_G5, NOTE_G5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_E5, NOTE_B4, NOTE_A4, NOTE_C5, NOTE_C5, NOTE_G4,
NOTE_A4, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_E5, NOTE_G5, NOTE_G5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_E5, NOTE_B4, NOTE_A4, NOTE_C5, NOTE_C5, NOTE_G4,
NOTE_A4, NOTE_C5, NOTE_C5, NOTE_B4
};
int melody2[]{
NOTE_E5, NOTE_G5, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_B4, NOTE_C5, NOTE_G4,
NOTE_A4, NOTE_C5, NOTE_C5, NOTE_B4,
};
// durations: 2 = half note, and 8/3,4,6,8,12. It appears that 8/2.9 is more accurate than 8/3.
float noteDurations[] = {
2, 8, 8, 8, 8, 2, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 2,
//chorus
8, 8, 4, 2, 8, 8, 4, 2, 8, 8, 4, 2, 8, 8, 4, 2, 8, 8, 4, 2, 8, 8, 4, 2, 8, 8, 4, 2, 8, 8, 4, 2
};
// calculates the number of elements in the melody array.
int musicLength=sizeof(melody)/sizeof('NOTE_F5');
void setup() {
pinMode(pPin, INPUT);
}
void loop() {
int pPinState=digitalRead(pPin);
if(pPinState==HIGH) {
ledState = 1;
}
if (pPinState==LOW and ledState ==1) {
ledState = 2;
ledOn = not ledOn;
}
if (ledOn && pPinState!=HIGH) {
for (int thisNote = 0; thisNote < musicLength; thisNote++) {
// blink the three LEDs in sequence
// calculate the note duration. change tempo by changing 2000 to other values
int noteDuration = 2000/noteDurations[thisNote];
tone(piezoPin, melody[thisNote],noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well
float pauseBetweenNotes = noteDuration * 1.40;
//split the delay into two parts and check to see
//whether the pushbutton is pressed to turn off
//the sound and light
delay(pauseBetweenNotes/2);
if(digitalRead(pPin)==HIGH) {
break;
}
delay(pauseBetweenNotes/2);
if(digitalRead(pPin)==HIGH) {
break;
}
}
}
}