Monday 9 May 2011

Arduino Happy Birthday source code

Arduino source code
/*  Happy Birthday Melody with flickering Candle
*  By Chris Hawkins
*  with modified code from the  Melody example
* (cleft) 2005 D. Cuartielles for K3
*
*
* Taken from (cleft) 2005 D. Cuartielles for K3
*
* The calculation of the tones is made following the mathematical
* operation:
*
*       timeHigh = period / 2 = 1 / (2 * toneFrequency)
*
* where the different tones are described as in the table:
*
* note  frequency  period  timeHigh
* c 1         261 Hz          3830  1915
* d 2         294 Hz          3400  1700
* e 3         329 Hz          3038  1519
* f 4         349 Hz          2864  1432
* g 5         392 Hz          2550  1275
* a 6         440 Hz          2272  1136
* b 7         493 Hz          2028 1014
* C 8         523 Hz         1912  956
*
* http://www.arduino.cc/en/Tutorial/Melody
*
*
*/

int speaker = 6;
int led1pin = 9; // RED LED
int led2pin = 10; // Yellow LED
int button =4; // state swicth to play music
int x = 0;
int buttonState = 0;
int length = 28; // the number of notes
char notes[] = "ccdcfe ccdcgf ccCafed bbafgf"; // 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,2};
int tempo = 300;

void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speaker, HIGH);
delayMicroseconds(tone);
digitalWrite(speaker, 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   };

// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}

void playmusic ()
{
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
}
else {
if (i % 2 == 0)
{
analogWrite (led1pin,200);
analogWrite (led2pin,100);
}
else {
analogWrite (led1pin,100);
analogWrite (led2pin,200);
}
playNote(notes[i], beats[i] * tempo);

}

// pause between notes
delay(tempo / 2);
}
digitalWrite (led1pin,LOW);
digitalWrite (led2pin,LOW);
}

void setup() {
pinMode(speaker, OUTPUT); /* Speaker to play tune */
pinMode(led1pin, OUTPUT); /* Red led from tri colour LED */
pinMode(led2pin, OUTPUT); /* Yellow led from tri colour LED */
pinMode (button, INPUT);  /* Start playing melody button */
}

void loop(){
buttonState = digitalRead (button); /* check if button pressed */
if (buttonState == HIGH){
playmusic();
}
}