/* Adopted from the Play Melody lab of D. Cuartielles -- See copyright notice below * * http://www.arduino.cc/en/Tutorial/PlayMelody * */ /* Play Melody * ----------- * * Program to play a simple melody * * Tones are created by quickly pulsing a speaker on and off * using PWM, to create signature frequencies. * * Each note has a frequency, created by varying the period of * vibration, measured in microseconds. We'll use pulse-width * modulation (PWM) to create that vibration. * We calculate the pulse-width to be half the period; we pulse * the speaker HIGH for 'pulse-width' microseconds, then LOW * for 'pulse-width' microseconds. * This pulsing creates a vibration of the desired frequency. * * (cleft) 2005 D. Cuartielles for K3 * Refactoring and comments 2006 clay.shirky@nyu.edu * See NOTES in comments at end for possible improvements */ // TONES ========================================== // Start by defining the relationship between // note, period, & frequency. #define c 3830 // 261 Hz #define d 3400 // 293 Hz #define e 3038 // 329 Hz #define f 2864 // 349 Hz #define g 2550 // 392 Hz #define a 2272 // 440 Hz #define b 2028 // 493 Hz #define C 1912 // 523 Hz #define D 1704 // 587 Hz #define E 1518 // 659 Hz #define F 1432 // 698 Hz #define enote 200 int scale[16] = { c, c, c, d, e, g, a, C, f, f, f, g, a, C, D, F} ; int speakerOut = 4; int presNote = 0 ; unsigned long noteStart = 0 ; void setup() { pinMode(speakerOut, OUTPUT); } // PLAY TONE ============================================== // Pulse the speaker to play a tone for a particular duration void playTone(int tone) { digitalWrite(speakerOut,HIGH); delayMicroseconds(tone / 2); digitalWrite(speakerOut, LOW); delayMicroseconds(tone / 2); } // I've got sunshine... void loop() { unsigned long now = millis() ; if (now > noteStart + enote) { presNote = (presNote+1) & 0xF ; noteStart = now ; } playTone(scale[presNote]) ; }