ezBuzzer Library - Melody Repeat Example
This example uses a piezo buzzer:
- Plays a melody once on background each time a button is pressed
- Stops playing a melody when another button is pressed
- Without using delay() function, this is a non-blocking example
Hardware Required
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.
About ezBuzzer Library
- Refer to Arduino - ezBuzzer Library Reference
Wiring Diagram
Arduino Code
Quick Steps
- Install ezBuzzer library. See How To
- Connect Arduino to PC via USB cable
- Open Arduino IDE, select the right board and port
- On Arduino IDE, Go to File Examples ezBuzzer Melody example
/*
Created by ArduinoGetStarted.com
This example code is in the public domain
Tutorial page: https://arduinogetstarted.com/library/arduino-melody-repeat-example
Library References: https://arduinogetstarted.com/tutorials/arduino-buzzer-library
This example uses a piezo buzzer:
+ play a melody on background
+ repeat the melody when it is ended
+ without using delay() function, this is a non-blocking example
*/
#include <ezBuzzer.h> // ezBuzzer library
const int BUZZER_PIN = 3;
ezBuzzer buzzer(BUZZER_PIN); // create ezBuzzer object that attach to a pin;
// notes in the melody:
int melody[] = {
NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_G5, NOTE_C5, NOTE_D5,
NOTE_E5,
NOTE_F5, NOTE_F5, NOTE_F5, NOTE_F5,
NOTE_F5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_D5, NOTE_D5, NOTE_E5,
NOTE_D5, NOTE_G5
};
// note durations: 4 = quarter note, 8 = eighth note, etc, also called tempo:
int noteDurations[] = {
8, 8, 4,
8, 8, 4,
8, 8, 8, 8,
2,
8, 8, 8, 8,
8, 8, 8, 16, 16,
8, 8, 8, 8,
4, 4
};
int noteLength;
void setup() {
Serial.begin(9600);
noteLength = sizeof(noteDurations) / sizeof(int);
}
void loop() {
buzzer.loop(); // MUST call the buzzer.loop() function in loop()
if (buzzer.getState() == BUZZER_IDLE) { // if stopped
buzzer.playMelody(melody, noteDurations, noteLength); // playing
}
}
- Click Upload button on Arduino IDE to upload code to Arduino
- You will hear "Jingle Bells" song repeatedly
Code Explanation
Read the line-by-line explanation in comment lines of source code!
※ NOTE THAT:
The above example code demonstrates how to use the ezBuzzer library to make a beep on Piezo Buzzer each time button is pressed. In practice, You may need to debounce for the button. Debouncing for the button is not easy for beginners. Fortunately, thanks to the ezButton library, We can do it easily.