Hello everyone. I am working on a project that plays music with piezo buzzers, but some parts of the song have overlapping notes. I can't seem to figure out how to play two notes on two different buzzers at once.
I'm working with a modified version of this code for playing music on a piezo buzzer that is found on the arduino site: https://www.arduino.cc/en/tutorial/melody
In order to play sharp notes, I converted the sequence of notes into a list of strings. The approach that I am taking in order to play multiple notes at once is creating a multidimensional array where each row has a different set of notes, which will be played on separate buzzers. Here is my code:
int speaker1=12;
int speaker2=11;
int speaker3=10;
int led=8;
int length=11;
int sets=2;
String gg="gg";
String aas="aas";
String b="b";
String c="c";
String cs="cs";
String d="d";
String ds="ds";
String e="e";
String f="f";
String fs="fs";
String g="g";
String gs="gs";
String a="a";
String as="as";
String B="B";
String C="C";
String D="D";
String DS="DS";
String CS="CS";
String E="E";
String s=" ";
String notes1[]={f, a, c, s, a, s, f, d, d, d, s};
String notes2[]={d, f, a, s, f, s, d, gg, gg, gg, s};
int beats[]={2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5};
int tempo=200;
String allNotes[2][11]={notes1, notes2};
void playTone(int tone, int duration){
for (long i=0; i<duration*1000L; i+=tone*2){
digitalWrite(speaker1, HIGH);
delayMicroseconds(tone);
digitalWrite(speaker1, LOW);
delayMicroseconds(tone);
}
}
void playNote(String note, int duration){
String names[]={"gg", "aas", "b", "c", "cs", "d", "ds", "e", "f", "fs", "g", "gs", "a", "as", "B", "C", "CS", "D", "DS", "E"};
int tones[]={2551, 2146, 2024, 1915, 1805, 1700, 1608, 1515, 1433, 1351, 1276, 1205, 1136, 1073, 1012, 956, 903, 852, 804, 759};
for (int i=0; i<20; i++){
if (names[i]==note){
playTone(tones[i], duration);
}
}
}
void setup(){
pinMode(speaker1, OUTPUT);
pinMode(led, OUTPUT);
}
void loop(){
for (int j=0; j<length; j++){
for (int i=0; i<sets; i++){
if (allNotes[i][j]==" "){
delay(beats[j]*tempo);
}
else{
playNote(allNotes[i][j], beats[j]*tempo);
}
delay(tempo/4);
}
}
}
Please note that I am a beginner and I haven't had a lot of time to refine my code. It may be a bit messy.
Do you have any suggestions of how to approach this?