I have a strange issue. I have 3 LEDs, each is supposed to beep with a correlated tone... Imagine the beginning of a racing game (beeping with traffic lights). Here's my code:
#include "pitches.h"
//Beginning Melody
int melody[] = {
NOTE_C3, NOTE_C3, NOTE_C4
};
//Beginning Note Durations
int noteDurations[] = {
2, 2, 1
};
int redLight = 3;
int yellowLight = 5;
int greenLight = 6;
void setup() {
Serial.begin(9600); //initialize serial communication
pinMode(redLight, OUTPUT);
pinMode(yellowLight, OUTPUT);
pinMode(greenLight, OUTPUT);
}
void loop() {
playBegin();
delay(5000);
}
void playBegin(){
int lightColor = 1;
for (int thisNote = 0; thisNote < 3; thisNote++) {
if(lightColor == 1){
analogWrite(redLight, HIGH);
}else if (lightColor == 2){
analogWrite(yellowLight, HIGH);
}else{
analogWrite(greenLight, HIGH);
}
lightColor++;
int noteDuration = 1000 / noteDurations[thisNote];
tone(11, melody[thisNote], noteDuration);
delay(1000);
noTone(11);
analogWrite(redLight, LOW);
analogWrite(yellowLight, LOW);
analogWrite(greenLight, LOW);
}
}
Originally, the 3 LEDs would light up correctly. The red light is plugged into Pin 3, the yellow light into Pin 5, and the green light into Pin 6. HOWEVER, when I added in the tones, the red light (in Pin 3) doesn't light up. The 3 tones still sound off correctly, and the yellow and green LEDs work perfectly fine. This is ONLY not working for the red LED, it just doesn't light up while the 1st tone happens.
When I take out the line of code where tone() is, it works fine and the red light will turn on at the correct time again. This is ONLY happening when the tone() function is included.
To be clear, this is the exact line of code that is affecting the red LED:
tone(11, melody[thisNote], noteDuration);
Furthermore, I swapped the pins of the yellow and red LEDs to see if it was an issue with the red LED, and it was not. It's whatever LED is plugged into Pin 3, and again, ONLY when the tone() function is in the code as well. I'm not sure how they're conflicting. This does not appear to be an issue with my hardware.
I'm working with Arduino Uno. If you need anymore info, let me know.
Thanks!
analogWrite()
coupled with the digial level ofHIGH
...?