I used toneMelody example code (sketch sample 02.Digital->toneMelody) on an Arduino UNO. Then I wanted to blink an LED with the melody.
Here's the code:
#include "pitches.h"
#define BLUE 3 // pin 3 does not blink. but, pin 9 ok.
#define GREEN 5
#define RED 6
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void setup() {
for (int thisNote = 0; thisNote < 8; thisNote++) {
analogWrite(RED, 0);
analogWrite(GREEN, 0);
analogWrite(BLUE, 0);
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
int color = melody[thisNote] % 5;
if(color == 0) {
analogWrite(RED, 200);
} else if(color == 1) {
analogWrite(GREEN, 200);
} else {
analogWrite(BLUE, 200);
}
delay(pauseBetweenNotes);
noTone(8);
}
analogWrite(RED, 0);
analogWrite(GREEN, 0);
analogWrite(BLUE, 0);
}
void loop() {
// no need to repeat the melody.
}
Unfortunately, pin 3 did not blink. But it worked when I changed pin 3 to pin 9.
To check whether pin 3 or Blue LED is broken, I checked with the following code.
#define BLUE 3
void setup() {
analogWrite(BLUE, 0);
}
void loop() {
for(int i = 0 ; i < 255 ; i ++) {
analogWrite(BLUE, i);
delay(10);
}
analogWrite(BLUE, 0);
}
This code worked. Blue LED blinked. Why couldn't pin 3 blink with toneMelody?
Thanks.