The delay() statement in the main loop will stop anything happening for 100ms. This is probably going to make your music sound jerky.
One solution is to turn the LED on before you ptay the note, play the note, and then turn it off afterwards. The LED is on while the note is playing and it sounds more seamless. Like this:
void loop() {
for (int i = 0; i < length; i++) {
if (notes == ' ') {
delay(beats * tempo); // rest
} else {
digitalWrite(ledPins[0], HIGH);
playNote(notes, beats * tempo);
digitalWrite(ledPins[0], LOW);
}
Now to address which LED pin you should be using. I am not sure how you have one LED per note when you have 8 notes { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' } and only 6 LED pins {2,3,4,5,6,7}, so that is one problem you need to fix. However, the key for you is that in playNote() you work out the array index of the note. That can be used as the array index of the ledpins array BUT you need to be turning the LED on and off to the playNote function:
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 < (sizeof(names)/sizeof(char)); i++) {
if (names[i] == note) {
digitalWrite(ledPins[i], HIGH);
playTone(tones[i], duration);
digitalWrite(ledPins[i], LOW);
}
}
}
You'll note I have also changed some other stuff in the function - 'magic' numbers like 8 are always a problem in code when you come back later in life, so writing a formula to work out the size is more maintainable (you may want to think about length = 15 in the same way). Also, the comparison needs to be to names indexed by i, not names - a big clue is if you are doing a loop and are not using the loop index anywhere in the loop then you may have a issue with the code. You have the same problem with the notes variable in the main loop, but I will let you discover and fix it for yourself ![]()
Clearly if you are using this new function you need to remove turning the LED on in the main loop:
void loop() {
for (int i = 0; i < length; i++) {
if (notes == ' ') {
delay(beats * tempo); // rest
} else {
playNote(notes, beats * tempo);
}