Arduino: Piezo speakers (buzzers)

[piezo buzzer] A "piezo buzzer" is basically a tiny speaker that you can connect directly to an Arduino.

"Piezoelectricity" is an effect where certain crystals will change shape when you apply electricity to them. By applying an electric signal at the right frequency, the crystal can make sound.

If your buzzer has a sticker on top of it, pull the sticker off. Connect one pin (it doesn't matter which one) to the Arduino's ground (Gnd) and the other end to digital pin 8.

From the Arduino, you can make sounds with a buzzer by using tone. You have to tell it which pin the buzzer is on, what frequency (in Hertz, Hz) you want, and how long (in milliseconds) you want it to keep making the tone.

tone(8, 1200, 500);   // tone on pin 8 at 1200 Hz for 1/2 second

How do you know what frequency to use? Young people can generally hear frequencies between about 20 Hz and 20,000 Hz; older people lose the high frequencies and may not be able to hear all the way up to 20,000. Of course it varies from person to person. Also, your buzzer may not be able to reproduce the whole range, especially the very high and low notes.

If you like, you can leave off the duration. In that case, it will keep making a tone until you tell it to stop by calling noTone(pin) or by calling tone() with a different frequency.

Okay, now try to make some noise! Here's a really simple program:

int SPEAKER = 8;    // The speaker is on pin 8

int freq = 50;      // Starting frequency

void setup()
    pinMode(SPEAKER, OUTPUT);

void loop()
    freq += 100;      // add 100 to freq

    if (freq > 8000)
        freq = 50;

    tone(SPEAKER, freq);


Once you've gotten your Arduino making noise, see if you can make the notes go down instead of up.

Or make random notes! You can get a random number between any two numbers like this:

  int rand = random(7, 20);
That would give you a number between 5 and 10. How would you use that to make your program play random notes?