Driving a piezo speaker with a PIC using pic-microcontroller,
A Pulse Width Modulation (PWM) output from a PIC microcontroller can be used to play tones on a piezo speaker. With this, musical scales and simple songs can be played on the piezo speaker.
Piezoelectric speakers operate by the converse piezoelectric effect: when a voltage is applied across the terminals, the piezoelectric material in the speaker deflects in one direction. Applying an alternating voltage, such as a square wave, will cause the material to vibrate and create a sound. A constant voltage will not produce a sound.
PWM was used to provide the alternating voltage to drive the speaker (Parallax 900-00001). The period of the PWM determines the tone that will be played; the duty cycle changes the volume.
The frequency range of the speaker was limited by the timer used by the PIC to control PWM, which is Timer 2. First, we determined the PWM frequencies that we could use, which was from about 2kHz to 10kHz. Setting the lowest frequency as our first note (C), a set of timer scaling values that correspond to frequencies that would play the basic notes of an octave of the diatonic scale was found. The period of the PWM is given by the following equation:
Since the pulse width ratio would be at 100% when the duty cycle exceeds the period of PWM, the range of duty cycle values that will produce a sound on the piezo speaker depends on the period of the PWM pulses. Duty cycle values of 1~125 will allow us to play all the notes defined in our code. For very small and very high duty cycles, the volume is low.
Frequency can be calculated by inverting the period. The table below displays the basic musical notes, their timer scaling value and the PWM frequencies in hertz.
|Note||Timer Scaling Value||Frequency (Hz)|
For more detail: Driving a piezo speaker with a PIC
From Schematic to PCB Production, Just Need One Tool
Free Circuit Design Software: learn to use Editor quickly and easily
Cheapest PCB: 10pcs 2-layers 10cm×10cm only $8.21, 3-day build time, 100% E-test
Current Project / Post can also be found using:
- picmicrocontroller piezoelectric speaker
- driving speakers from a microcobtroller