Created
November 26, 2012 18:40
-
-
Save lfzawacki/4149836 to your computer and use it in GitHub Desktop.
buzzer with notes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Buzzer example function for the CEM-1203 buzzer (Sparkfun's part #COM-07950). | |
// by Rob Faludi | |
// http://www.faludi.com | |
// Matehacked by Lucas and Jerônimo | |
int noteToFreq(int note) | |
{ | |
return (int) pow(2, (double)note/12) * 440; | |
} | |
void setup() { | |
pinMode(4, OUTPUT); // set a pin for buzzer output | |
pinMode(2, OUTPUT); | |
} | |
void loop() { | |
buzz(2, noteToFreq(39), 50); | |
buzz(4, noteToFreq(36), 50); | |
delay(25); | |
buzz(2, noteToFreq(42), 100); | |
buzz(4, noteToFreq(39), 200); | |
delay(25); | |
buzz(2, noteToFreq(45), 150); | |
buzz(4, noteToFreq(41), 100); | |
delay(25); | |
buzz(2, noteToFreq(42), 100); | |
buzz(4, noteToFreq(39), 150); | |
delay(25); | |
} | |
void buzz(int targetPin, long frequency, long length) { | |
long delayValue = 1000000/frequency/2; // calculate the delay value between transitions | |
//// 1 second's worth of microseconds, divided by the frequency, then split in half since | |
//// there are two phases to each cycle | |
long numCycles = frequency * length/ 1000; // calculate the number of cycles for proper timing | |
//// multiply frequency, which is really cycles per second, by the number of seconds to | |
//// get the total number of cycles to produce | |
for (long i=0; i < numCycles; i++){ // for the calculated length of time... | |
digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphram | |
delayMicroseconds(delayValue); // wait for the calculated delay value | |
digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphram | |
delayMicroseconds(delayValue); // wait againf or the calculated delay value | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment