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.

Driving a piezo speaker with a PIC

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.

PWM Period

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.

Driving a piezo speaker with a PIC

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)
C 255 2441
D 227 2741
E 204 3048
F 191 3255
G 170 3654
A 153 4058
B 136 4562
C2 127 4882



For more detail: Driving a piezo speaker with a PIC

About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us: