Introduction
This tutorial shows how to hook up a piezo buzzer and an Arduino Uno board to make a simple sound alarm whose volume can be adjusted . The buzzer is operating at low current therefore it can be interfaced directly to the Arduino board.
Parts used
- arduino uno rev3
- buzzer module
- breadboard
- jumper wires
Breadboard layout
the negative lead (black wire) is connected to the arduino’s gnd pin while the positive lead (red wire)is connected to the arduino’s digital pin 9.
Wiring
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//setup void setup() { //set pin 9 as an output pinMode(9, OUTPUT); //beep 3 times each with a duration of 50 milliseconds beep(50); beep(50); beep(50); //wait for a second delay(1000); } //loop void loop() { //beep for a duration of 200 milliseconds beep (200); //call the beep function and pass a parameter to it } //the beep function void beep(unsigned char delayms) { analogWrite(9, 20);//he two values are pin number and value to write to it(0-255) delay(delayms);//this value was passed from the main loop analogWrite(9, 0); delay(delayms); } |
To test if the buzzer is working you can use the simple blink sketch on pin 9. With a delay of one second the buzzer will beep for every one second in an infinite loop.You can use the analog write function to change the intensity of the beep too.
How the code works
sets digital pin 9 an output
1 |
pinMode(9, OUTPUT); |
beep for 50 milliseconds
1 |
beep(50); |
beep for 50 milliseconds
1 |
beep(50); |
beep for 50 milliseconds
1 |
beep(50); |
delay for 1 second before going into the main loop
1 |
delay(1000); |
this code snippet beeps 3 times at startup and then beeps continuously at a slower rate
1 2 3 4 5 |
void beep(unsigned char delayms) { analogWrite(9,20); delay(delayms); .... |
we have created the function beep() which will send the pwm signal to the buzzer waits for a small delay and then turns it off for another small delay
1 |
beep (200); |
the delay is passed as a parameter when calling the beep() function
Running the Code
Applications
this tutorial can be integrated into other projects to provide audio feedback .