/* Tom Haas, 20120611 electronic_birthday_card.ino This sketch is for an interactive birthday card that will play "Happy Birthday" and blink some LEDs upon tripping a switch. The switch is a reed switch, tripped by a magnet, and the LEDs are yellow LEDs that blink in time with the "Happy Birthday" song, played by a piezo speaker. Uses the "Tone" Arduino library by bhagman@roguerobotics.com. In Tone.cpp, #include --> #include in order for it to work on my install. */ #include #define ON HIGH #define OFF LOW // For input/output set up int speakerPin = 9; int ledPins[] = { 5, 6 }; int inputPin = 10; //reed switch int inputVal = 0; // Calculate number of LEDs int ledCount = sizeof(ledPins) / sizeof(int); Tone makeTone; // Song to play int notes[] = { NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_F4, NOTE_E4, 0, NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_G4, NOTE_F4, 0, NOTE_C4, NOTE_C4, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_E4, NOTE_D4, 0, NOTE_AS4, NOTE_AS4, NOTE_A4, NOTE_F4, NOTE_G4, NOTE_F4, 0 }; // notes to play; see Tone.h for frequencies; 0 --> PAUSE int songLength = sizeof(notes) / sizeof(int); // Calculate song length int beats[] = { 1, 1, 2, 2, 2, 4, 2, 1, 1, 2, 2, 2, 4, 2, 1, 1, 2, 2, 2, 2, 4, 2, 1, 1, 2, 2, 2, 4, 4 }; // number of beats for each note int numberBeats = sizeof(beats) / sizeof(int); // Calculate number of beats int tempo = 200; // in milliseconds // End song void animateComponents(int note, int beat, int tempo, int leds[], int numberLeds) { makeTone.stop(); // speaker reset ledSwitch(leds, numberLeds, ON); makeTone.play(note); // play tone delay(tempo * beat); // for specified number of beats makeTone.stop(); // speaker reset ledSwitch(leds, numberLeds, OFF); delay(tempo / 2); // pause between notes } void playPause(int beat, int tempo) { delay(tempo * beat); // pause for specified number of beats delay(tempo / 2); // pause between notes } void ledSwitch(int leds[], int numberLeds, int pinVoltage) { for (int i = 0; i < numberLeds; i++) { digitalWrite(leds[i], pinVoltage); // turn on/off LED } } void setup() { for(int i = 0; i < ledCount; i++){ pinMode(ledPins[i], OUTPUT); // set up LEDs for writing } pinMode(inputPin, INPUT); // set up reed switch makeTone.begin(speakerPin); // set up piezo speaker } void loop() { inputVal = digitalRead(inputPin); // default (not switched) = HIGH if (inputVal == LOW) { // do nothing until LOW, then play song if (songLength > 0 && numberBeats > 0 && tempo > 0 && songLength == numberBeats) { // Simple song error check for (int i = 0; i < songLength; i++) { // loop through song if (notes[i] == 0) { // PAUSE playPause(beats[i], tempo); } else { animateComponents(notes[i], beats[i], tempo, ledPins, ledCount); // make sound & light up LEDs } } } else { // Play on song error makeTone.stop(); makeTone.play(NOTE_C2); delay(1000); makeTone.play(NOTE_C1); delay(2000); makeTone.stop(); } } }