ezBuzzer Library - Beep Example

This example uses a piezo buzzer:

Hardware Required

1×Arduino UNO or Genuino UNO
1×USB 2.0 cable type A/B
1×Piezo Buzzer
1×Breadboard-mount Button with Cap
1×Breadboard-mount Button Kit
1×Panel-mount Push Button
1×Breadboard
1×Jumper Wires
1×(Recommended) Screw Terminal Block Shield for Arduino Uno
1×(Recommended) Breadboard Shield For Arduino Uno
1×(Recommended) Enclosure For Arduino Uno
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 Piezo Buzzer and Button

If you do not know about piezo buzzer and button (pinout, how it works, how to program ...), learn about them in the following tutorials:

About ezBuzzer Library

Wiring Diagram

Arduino Button Piezo Buzzer Wiring Diagram

This image is created using Fritzing. Click to enlarge image

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 Beep example
/* Created by ArduinoGetStarted.com This example code is in the public domain Tutorial page: https://arduinogetstarted.com/library/arduino-beep-example Library References: https://arduinogetstarted.com/tutorials/arduino-buzzer-library This example uses a piezo buzzer: + generates a 100ms beep on background when a button is pressed + without using delay() function, this is a non-blocking example */ #include <ezBuzzer.h> // ezBuzzer library const int BUTTON_PIN = 7; const int BUZZER_PIN = 3; int lastButtonState = HIGH; // the previous state from the input pin ezBuzzer buzzer(BUZZER_PIN); // create ezBuzzer object that attach to a pin; void setup() { Serial.begin(9600); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { buzzer.loop(); // MUST call the buzzer.loop() function in loop() int currentState = digitalRead(BUTTON_PIN); if (lastButtonState == HIGH && currentState == LOW) { Serial.println("The button is pressed"); buzzer.beep(100); // generates a 100ms beep } lastButtonState = currentState; }
  • Click Upload button on Arduino IDE to upload code to Arduino
Arduino IDE Upload Code
  • Press and release the button some time
  • You will hear a beep each time you press button.

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.

The Best Arduino Starter Kit

※ OUR MESSAGES