/* * Arduino Jingle Bells. Reconstructed from code snippets here: * http://www.uchobby.com/index.php/2007/11/22/arduino-sound-part-3-playing-a-melody/ */ #define LEDPIN 13 #define OUTPIN 9 #define FREQ_A3 220.00 #define FREQ_AS3 233.08 #define FREQ_BF3 233.08 #define FREQ_B3 246.94 #define FREQ_C4 261.63 //Middle C #define FREQ_CS4 277.18 #define FREQ_DF4 277.18 #define FREQ_D4 293.66 #define FREQ_DS4 311.13 #define FREQ_E4 329.63 #define FREQ_F4 349.23 #define FREQ_G4 392.00 #define FREQ_A4 440.00 #define FREQ_B4 493.88 #define FREQ_C5 523.25 #define FREQ_D5 587.33 #define WHOLE_NOTE_TIME 2000 void Sound(float freq, int durationMS, int outputPin) { int halfPeriod; float period; int durationCycles; //Check for rest, 0 frequency is a rest for durationMS. if(freq==0.0) { //0 frequency so we stay quiet for duration delay (durationMS); } else { //Frequency is not zero so we have work to do // turn on output pin pinMode(outputPin, OUTPUT); //calculate the period or cycle time for the given frequency period=1/freq; //Take the reciprocal to get time in seconds period=period*1.0E6; //to covert seconds to uS. //divide that by 2 to get the 1/2 cycle time. convert to int at the same time halfPeriod = (int)(period/2.0) - 7; // subtract 7 us to make up for digitalWrite overhead // calculate cycles for duration. durationCycles = (int)(((float)durationMS*1000.0)/period); // play note for duration ms for (int i=0; i