It's super easy to use piezo buzzers with Arduino's tone()
function. Just wire up the buzzer to pin 10 and then to GND with a resistor. The tone()
function needs 2 arguments, but can take three:
delay()
function following the tone instead.
int buzzerPin = 10;
void setup() {
pinMode(buzzerPin, OUTPUT);
}
void loop() {
tone(buzzerPin, 1000, 500);
delay(1000);
}
Note: there have been some issues with the tone()
function not working properly with some microcontrollers. In some cases, the tone()
function causes the program to not compile. In other cases, it compiles fine but fails to produce sounds. If you experience problems, we recommend pasting the myTone()
function below, and using it in the same way. So the above example would look like this:
int buzzerPin = 10;
void setup() {
pinMode(buzzerPin, OUTPUT);
}
void loop() {
myTone(buzzerPin, 262, 500);
delay(1000);
}
void myTone(int pin, int frequency, int duration){
int startTime = millis();
int period = 1000000/frequency;
while ((millis() - startTime) < duration){
digitalWrite(pin, HIGH);
delayMicroseconds(period/2);
digitalWrite(pin, LOW);
delayMicroseconds(period/2);
}
}
The myTone()
function calculates the period of the wave that produces the desired frequency (in Hz, or cycles per second). Middle C is about 262 Hz. If we divide 1 million (the number of microseconds in a second) over 262 cycles per second, we get a period (or cycle) of about 3,817 microseconds. We want to turn our piezo on for half that time, then off for the remaining half, thereby making a square wave. In the above code, the square wave plays for half a second, then is silent for one second during the subsequent delay.
Some things to keep in mind when using buzzers:
Being able to combine multiple example sketches into one is a very useful skill. See if you can combine the buzzer with a sketch you made for an input device like a potentiometer.
Getting a buzzer to make noise is simple, but composing music is not. There are plenty of reference tables for frequencies of musical notes, but timing notes is also tricky. Check out some examples of classic tunes arranged for Arduino:
For more information on sound generation with the Arduino, see this guide: