### Silence or noise? Whatever you like, the buzzer is needed....

A buzzer or beeper is an audio signalling device, which may be mechanical, electromechanical, or piezoelectric (piezo for short). Typical uses of buzzers and beepers include alarm devices, timers, and confirmation of user input such as a mouse click or keystroke.

The one that we 'll use in this lesson is the piezo buzzer which looks like the one below:
So as you can see, there is a (+) leg which goes to the digital pin of the NodeMCU that we choose and the other pin goes to the GND pin.

Build the diagram below to experiment with the sound of buzzer:

Then we can code our circuit to just beep forever, with the code below:

void setup()
{

}

void loop()
{
tone(14, 494, 500);
delay(1000);
}

Copy the code to Arduino IDE, upload it to NodeMCU and listen to the beep.
We notice here that the setup() section is empty and the loop() section contains a tone() function and an one second delay. The three numbers inside the tone() function represent: the pin we send the sound (D5 or 14 in our case), the frequency of the sound wave we send and the duration of the tone.
You can change the last two parameters and play with the speed of the beeps and the sound of them.

But instead of listening just beeps, we can program our circuit to compose melodies, using notes.

An example of this, is below:

int speakerPin = 14;

int length = 15; // the number of notes
char notes[] = "ccggaagffeeddc "; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;

void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}

void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}

void setup() {
pinMode(speakerPin, OUTPUT);
}

void loop() {
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}

// pause between notes
delay(tempo / 2);
}
}

You can copy that, paste it in the Arduino IDE and then upload it to the NodeMCU. You may need to come close to the buzzer in order to hear the melody.