Tutorial: Active Buzzer
Buzzers
Transducer - converts electrical energy into mechanical energy
Two categories: Active and Passive (you have one of each type in your kit)
Active Buzzer is the slightly taller one, with a solid, plastic coat on the bottom and a label that says to remove it after washing.
Only requires an external DC voltage to make it sound (batteries or USB from Arduino)
An active buzzer has a built-in oscillating source, so it will make sounds when electrified.
Can turn it on or off to make various sounds
You can use a 100 Ω resistor with it but its optional.
Uxcell a12081600ux0477 12 mm Diameter DC 5V 2 Terminals Electronic Continuous Sound Buzzer
Use simple code to turn it on and off:
int buzzerPin = 4; // the setup function runs once void setup() { // initialize digital pin 7 as an output. pinMode(buzzerPin, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(buzzerPin, HIGH); // turn the buzzer on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(buzzerPin, LOW); // turn the buzzer off by making the voltage LOW delay(1000); // wait for a second }
Another Approach: Write a function
// Buzzer example function for the CEM-1203 buzzer (Sparkfun's part #COM-07950).
// by Rob Faludi
// http://www.faludi.com
void setup() {
pinMode(4, OUTPUT); // set a pin for buzzer output
}
void loop() {
buzz(4, 2500, 500); // buzz the buzzer on pin 4 at 2500Hz for 500 milliseconds
delay(1000); // wait a bit between buzzes
}
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 again for the calculated delay value
}
}