Hey! I'm new into Arduino and i'm having some trouble with my project. What I'm basically trying to do is to have a pattern of lights along four LED lights (it's a simple proof of concept), while a buzzer plays Jingle Bells at the same time.
My problem is that I can't figure out how to write my code in order to make it simultaneous. What happens is that the lights turn on in the pattern I designed, and when the pattern is finished, the song starts playing. Here's my code:
int speakerPin = 12;
int length = 29; // the number of notes
char notes[] = "eeeeeeegcdefffffeeeeddedg"; // this is the code for the song I copied
int beats[] = { 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 4,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1 };
int tempo = 250;
void setup() {
pinMode(13, INPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
}
void line() { //this is my pattern
digitalWrite(11, HIGH);
delay(500);
digitalWrite(10, HIGH);
delay(500);
digitalWrite(11, LOW);
digitalWrite(9, HIGH);
delay(500);
digitalWrite(10, LOW);
digitalWrite(8, HIGH);
delay(500);
digitalWrite(9, LOW);
delay(500);
digitalWrite(8, LOW);
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 };
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
void loop() {
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}
}
}
I don't know how to call the function "line()" in the void loop for the song and the light pattern be simultaneous, and after a few tries I deleted my attempts at doing it.
Any help is useful! Thank you very much!