Friday, March 5, 2010

LED Project - Assignment 1




// Melody by Adam Randall
// This is a program designed to output LED's when notes are played
// through a speaker. Below is the code used.

int speakerPin = 12; // output Speaker
int led1 = 9; // output LED1
int led2 = 8; // output LED2
int led3 = 7; // output LED3
int led4 = 6; // output LED4
int led5 = 5; // output LED5
int led6 = 4; // output LED6

int length = 24; // the number of notes
char notes[] = "ggcGfcg ggcGfcg bcAcAbA "; // a space represents a rest
int beats[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int tempo = 300;

void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH); // speaker on
delayMicroseconds(tone); // delay
digitalWrite(speakerPin, LOW); // spaker off
delayMicroseconds(tone);
}
}

void playNote(char note, int duration) {
char names[] = {'d', 'e', 'f', 'g', 'a', 'b', 'c', 'G', 'A'}; // notes
int tones[] = {587, 659, 698, 784, 880, 988, 1047, 831, 932 }; // frequency

if (note == 'c') {
digitalWrite (led1, HIGH); // LED1 on
delay (50); //delay
digitalWrite (led1, LOW); // LED1 off
}
else if (note == 'g') {
digitalWrite (led2, HIGH); // LED2 on
delay (50); //delay
digitalWrite (led2, LOW); // LED2 off
}
else if (note == 'G') {
digitalWrite (led3, HIGH); // LED3 on
delay (50); //delay
digitalWrite (led3, LOW); // LED3 off
}
else if (note == 'b') {
digitalWrite (led4, HIGH); // LED4 on
delay (50); //delay
digitalWrite (led4, LOW); // LED4 off
}
else if (note == 'A') {
digitalWrite (led5, HIGH); // LED5 on
delay (50); //delay
digitalWrite (led5, LOW); // LED5 off
}
else if (note == 'f') {
digitalWrite (led6, HIGH); // LED6 on
delay (50); //delay
digitalWrite (led6, LOW); // LED6 off
}

// play the tone corresponding to the note name
for (int i = 0; i < 20; i++) {
if (names[i] == note) {

playTone(tones[i], duration);
}
}
}

void setup() {
pinMode(speakerPin, 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);
}

// pause between notes
delay(tempo / 2);
}
}



Below is a video of th assignment at work:

No comments:

Post a Comment