/

Arduino Project: Generating Sound with a Passive Buzzer

Arduino Project: Generating Sound with a Passive Buzzer

In this Arduino project, we will be using a passive buzzer to generate sound. Similar to the active buzzer example, you will need to connect the buzzer to the Arduino.

Arduino Project Passive Buzzer

The buzzer has a positive “+” pole, which can be connected using a red wire (a good habit to follow). Connect the negative “-“ wire to the GND on the Arduino and the “+” wire to a digital output pin. In this case, we will be using pin #8.

Passive Buzzer Connection

For generating sound, the Arduino language provides a function called tone(), which is perfect for working with a passive buzzer. It allows us to play a specific frequency on the buzzer pin for a specified duration.

Here is an example of generating sounds using tone():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int duration = 500;

void setup() {

}

void loop() {
tone(8, 1400, duration);
delay(200);
tone(8, 800, duration);
delay(200);
tone(8, 1800, duration);
delay(200);
tone(8, 600, duration);
delay(200);
}

You can even play actual songs using tone() by combining different frequencies. Here is an example of a program that plays a melody using the pitches.h library:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Melody

Plays a melody

circuit:
- 8 ohm speaker on digital pin 8

created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Tone
*/

#include "pitches.h"

// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {

// calculate the note duration, take one second divided by the note type.
// For example, a quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);

// set a minimum time between notes to distinguish them.
// The note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}

void loop() {
// no need to repeat the melody.
}

By utilizing multiple buzzers, you can create melodies with multiple notes. You can also combine sound generation with user input to create interactive projects, such as a toy keyboard with different sounds.

tags: [“Arduino”, “passive buzzer”, “sound generation”, “tone()”, “melodies”, “user input”, “interactive projects”]