8-Bit CCP Pulse Width Modulation on PIC Devices
Pulse Width Modulation (PWM) is a common peripheral on almost every PIC® MCU device. PWM is a way to use a digital output to vary the on, or high time, to create a variable output or square wave (see the accompanying figure). If the PWM signal runs at a fixed frequency, then changing the high time of the signal will also change the low time of the signal. The amount of time the signal is high is typically called the pulse width. That pulse width relative to the period of the signal is called the duty cycle. The period of the signal is defined as the time from one rising edge to the next rising edge of the square wave signal and is inversely proportional to the PWM frequency.
The period can easily be calculated by using the formula:
(1) Period = 1 / Frequency
For example, a 1 kHz frequency will give us a 1 millisecond period.
Using PWM gets very interesting because there are many applications for it. Simplest of all is driving some kind of low-pass filter. By driving a simple Resistor/Capacitor (RC) low-pass filter circuit (see the accompanying figure) directly from the microcontroller’s PWM port, the variable pulse width will be averaged out by the capacitor’s charge and discharge rate through the resistor. With enough filtering, the digital PWM signal can be converted into an analog voltage and used as a low cost digital to analog (D/A) converter.