#define c 383 // 261 Hz #define d 340 // 294 Hz #define e 203 // 329 Hz #define f 186 // 349 Hz #define g 155 // 392 Hz #define a 127 // 440 Hz #define b 202 // 493 Hz #define n 400 // Define a special note, 'R', to represent a rest #define R 0 // SETUP ============================================ // Set up speaker on a PWM pin (digital 9, 10 or 11) int speakerOut = 9; int speaker2Out = 8; // Do we want debugging on serial out? 1 for yes, 0 for no int DEBUG = 1; void setup() { pinMode(speakerOut, OUTPUT); pinMode(speaker2Out, OUTPUT); if (DEBUG) { Serial.begin(9600); // Set serial out if we want debugging } } // MELODY and TIMING ======================================= // melody[] is an array of notes, accompanied by beats[], // which sets each note's relative length (higher #, longer note) int melody[] = { n, n, n, n, n, n, n, n, n, n, n, n }; int beats[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; int MAX_COUNT = sizeof(melody) / 2; // Melody length, for looping. // Set overall tempo long tempo = 100; // Set length of pause between notes int pause = 1000; // Loop variable to increase Rest length int rest_count = 0; //<-BLETCHEROUS HACK; See NOTES // Initialize core variables int tone = 0; int beat = 0; long duration = 0; // PLAY TONE ============================================== // Pulse the speaker to play a tone for a particular duration void playTone() { long elapsed_time = 0; if (tone > 0) { // if this isn't a Rest beat, while the tone has // played less long than 'duration', pulse speaker HIGH and LOW while (elapsed_time < duration) { digitalWrite(speakerOut,HIGH); delayMicroseconds(tone); // DOWN digitalWrite(speakerOut, LOW); delayMicroseconds(tone / 4); digitalWrite(speaker2Out,HIGH); delayMicroseconds(tone / 5); // DOWN digitalWrite(speaker2Out, LOW); delayMicroseconds(tone / 2); // Keep track of how long we pulsed elapsed_time += (tone); } } else { // Rest beat; loop times delay for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count delayMicroseconds(duration); } } } // LET THE WILD RUMPUS BEGIN ============================= void loop() { // Set up a counter to pull from melody[] and beats[] for (int i=0; i