Tuesday, April 21, 2009

Driving a Piezoelectric Speaker with a PIC

Piezoelectric speakers are really cool. You can get them inexpensively from most hobby electronics stores, take them out of PCs, and so on. You can directly connect them to your microcontroller (resistor recommended) and generate any tone you want.

Simply connect one end of the speaker to an output pin on your PIC and connect the other end to GND for the simplest configuration. You make the speaker “tick” by passing current through it. By rapidly turning the output pin on and off, you generate a tone. Here’s a very simple example program that turns the output pin on and off via software:

#include "main.h"
#define SLEEP 1000

void main() {
    while(true) {

Pin B6 (in my case) is the speaker output. Pin C0 is an output to an LED (for testing, it is not needed). You can change the value of the SLEEP define for varying frequency of sound.

However, there is another way that this can be done (more reliably) – using the PIC’s internal PWM (from CCP module). You can generate very precise frequencies that way.

No comments:

Post a Comment