Electronics Projects: How to Use a Piezo Speaker with a BASIC Stamp
You can add interesting sound effects and simple music to your electronics projects using the BASIC Stamp Activity Kit. The kit comes with a small piezoelectric speaker, which you can connect directly to an I/O pin to create beautiful music.
Well, the music probably won’t be so beautiful, but you can coax the BASIC Stamp into emitting a variety of squeaks, burps, and squelches that resemble musical notes. And you can create interesting sound effects like police sirens or chirping crickets.
If you didn’t purchase the BASIC Stamp Activity Kit, you can order the piezo speaker directly from the Parallax website (www.parallax.com) for $1.95.
Note that the piezo speaker is polarized, so when you connect it to an I/O pin, be sure to connect the + terminal to the I/O pin and the other terminal to Vss (ground).
Program with the FREQOUT command
Programming a piezo speaker is remarkably simple. PBASIC includes a command called FREQOUT that sends a frequency of your choice to an output pin. Thus, you can create an audible tone on a piezo speaker by using the FREQOUT command, using the following syntax:
FREQOUT pin, duration, frequency
Here’s how that syntax works:
pin is simply the pin number that you want to send the frequency to.
duration is simply the length of time in milliseconds you want the frequency to play. And
frequency is the frequency in hertz that you want to generate.
For example, the following command generates a 2,000 Hz frequency for five seconds on pin 8:
FREQOUT 8, 5000, 2000
You can easily create a beeping sound by alternately sending short bursts of a frequency to the speaker followed by a brief pause. For example:
DO FREQOUT 8,250, 1500 PAUSE 250 LOOP
This code repeatedly sends a 1,500 Hz signal for a quarter of a second, and then pauses for a quarter of a second. The result is a beep-beep-beep sound.
Test the piezo speaker
This project shows how to build a simple circuit that connects a piezo speaker to a BASIC Stamp so you can create audible output; two pushbuttons vary the sound output.
The piezo speaker here is actually very quiet. This is normal; the piezo speaker draws just 1 mA, and so can’t make a lot of noise. The speaker is loudest with frequencies between 4,500 and 5,500 Hz.