Make a Sound with a Piezo Buzzer

We can make simple tones with a buzzer.

Written By: Cherie Tan

Dash icon
Difficulty
Easy
Steps icon
Steps
5
Piezo buzzers are simple audio-signalling devices that can generate sounds.

In this guide, we will learn how to create basic beeps and tones with the piezo buzzer and an Arduino. 

Complete this guide to understand the basics involved in using a buzzer. Then you can utilise it for more advanced projects!

Step 1 Plug your buzzer in

Plug your Buzzer in so that the positive pin is on the right hand side.
There are markings on the buzzer which indicate the positive and negative pins.

Step 2 Connect the Digital Pin 9 to the Buzzer

Connect the Digital Pin 9 to the Buzzer's positive pin.

Step 3 Connect the Ground to the Buzzer

Connect the Ground to the Buzzer's negative pin.

Step 4 Give us a beep.....!

const int buzzer = 9; //buzzer to arduino pin 9


void setup(){

  pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output

}

void loop(){

  tone(buzzer, 1000);
  delay(1000);        // on for 1 sec
  noTone(buzzer);     // Stop sound
  delay(1000);        // on for 1sec

}
Copy this code to the Arduino IDE
Upload the code and your buzzer should start to beep on and off

Step 5 Jingle all the way!

int speakerPin = 5;
int length = 26;
char notes[] = "eeeeeeegcde fffffeeeeddedg";
int beats[] = { 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2};

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);
  }
}
A quick search for "Arduino Buzzer Jingle Bells" turned up this code by elubow
Give it a try!
Note - look at the code and see you need to change buzzer jumper wire to Pin 5 or you could change the code to utilise pin 9.