/* * LilyPad tutorial: sound * * Uses a LilyPad speaker module to produce simple musical notes * For a chart of the frequencies of different notes see: * http://www.phy.mtu.edu/~suits/notefreqs.html */ int ledPin = 13; // LED is connected to digital pin 13 int speakerPin = 9; // speaker connected to digital pin 9 int knockerPin = 12; // The knocker to complete the circuit // The pins that will be used as chime inputs int chimePins[] = {14, 18, 2, 5, 10}; int chimePinsLength = 5; // Frequencies of notes to play int notes[] = {523, 587, 698, 784, 880, 1047, 1175, 1397}; int notesLength = 8; // An amplitude envelope for the tone. int envelope[] = {30, 60, 50, 40, 30, 20, 10, 5, 1, 1, 1, 1, 1, 1, 1, 1}; int envelopeLength = 16; int maxAmplitude = 64; // if this is too high, note lengths get funky; too low, and it's choppy void setup() { pinMode(ledPin, OUTPUT); // sets the ledPin to be an output pinMode(speakerPin, OUTPUT); // sets the speakerPin to be an output windChimesInit(); Serial.begin(9600); } void windChimesInit() { pinMode(knockerPin, OUTPUT); digitalWrite(knockerPin, LOW); int x; for (x = 0; x < chimePinsLength; x++) { pinMode(chimePins[x], INPUT); digitalWrite(chimePins[x], HIGH); } } void loop() { windChimes(); //scale(); //delay(1000); // delay for 1 second } // Make noise void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds) { int x; long delayAmount = (long)(1000000/frequencyInHertz); long delayChunk = delayAmount / maxAmplitude; long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2)); int envChunk = loopTime / envelopeLength; long onDelay; long offDelay; int amplitude; for (x=0;x 0) { digitalWrite(speakerPin,HIGH); delayMicroseconds(onDelay); } if (offDelay > 0) { digitalWrite(speakerPin,LOW); delayMicroseconds(offDelay); } } } // Polls inputs specified in chimePins, and rings a chime if one is low. void windChimes() { int x; for (x = 0; x < chimePinsLength; x++) { if (digitalRead(chimePins[x]) == LOW) { digitalWrite(ledPin, HIGH); beep(speakerPin, notes[x], 500); Serial.println(notes[x]); digitalWrite(ledPin, LOW); } } } void randomNotes() { int x; digitalWrite(ledPin,HIGH); //turn on the LED for (x = 0; x < 8; x++) { beep(speakerPin, notes[random(0, notesLength)], 500); } digitalWrite(ledPin,LOW); //turn off the LED } void scale () { int x; digitalWrite(ledPin,HIGH); //turn on the LED for (x = 0; x < notesLength; x++) { beep(speakerPin,notes[x],500); //C: play the note C (C7 from the chart linked to above) for 500ms } digitalWrite(ledPin,LOW); //turn off the LED }