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() {
    setup_adc_ports(NO_ANALOGS|VSS_VDD);    
    setup_oscillator(OSC_8MHZ);
    setup_uart(9600);
    
    while(true) {
        output_high(PIN_B6);
        output_high(PIN_C0);
        delay_us(SLEEP);
        output_low(PIN_B6);
        output_low(PIN_C0);
        delay_us(SLEEP);
    }
}

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