I'm doing a project where I'm trying to correspond a flashing led with a note made by my piezo element. I have 6 different notes and therefore 6 leds. Some leds will flash more than others depending on how many times that note is played in the song (twinkle twinkle little star)
I'm trying to add an if then statement in the loop but I do not know how to do one in this situation. I'm trying to say if note 'a' played led '3' high for example (not literal example in this code) but I do not know how to separate the piezo notes from their current 'i' increments
here is what i have so far
int speakerPin = 9;
int length = 15; // the number of notes
char notes[] = "ccggaagffeeddc "; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;
int ledPins[] = {2,3,4,5,6,7};
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
void setup() {
pinMode(speakerPin, OUTPUT);
pinMode(ledPins[0],OUTPUT);
pinMode(ledPins[1],OUTPUT);
pinMode(ledPins[2],OUTPUT);
pinMode(ledPins[3],OUTPUT);
pinMode(ledPins[4],OUTPUT);
pinMode(ledPins[5],OUTPUT);
}
void loop() {
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
digitalWrite(ledPins[0], HIGH);
delay (100);
digitalWrite(ledPins[0], LOW);
}
Moderator edit: There are really, really good reasons we use tags when posting code.
Did you read this before posting?