PIC Microcontroller and PWM Generation
PWM signals are one of the most basic and widely used methods for generating analog voltages from digital signals. DC Motor Speed Control, Sine Wave Inverters, Brightness Control, and more applications are among them.
PWM signals are ON-OFF (HIGH or LOW) signals (hence the name Pulse) whose HIGH or ON duration is varied (thus the name Width Modulation) to meet our needs. Duty Cycle is the percentage of time that the signal is ON compared to the overall time period.
CCP modules, which are included with most PIC Microcontrollers, may readily generate PWM waves. CCP stands for Capture, Compare, and PWM, which implies it can perform Capture, Compare, and PWM operations.
PWM signals can be generated in our PIC Microcontroller by using the CCP (Compare Capture PWM) module.
The following registers are used to generate PWM signals using our PIC MCU:
- CCP1CON (CCP1 control Register
- T2CON (Timer 2 Control Register)
- PR2 (Timer 2 modules Period Register)
- CCPR1L (CCP Register 1 Low)
Calculations
- PR2 : Timer 2 period register ( decides frequency of PWM signal)
- PR2={ Fosc /( Fpwm*4*N)}-1
- Where N is prescalar value (T2CON register) (we consider it as 16)
- If FOSC = 48 MHz and N=16 and PWM frequency = 5KHz
- Then PR2 =149 (Count related to frequency of PWM signal)
Duty Cycle:
- Duty cycle count should be stored in CCPR1L
- CCPR1L = PR2 * Duty cycle
- For 20% Duty cycle
- CCPR1L = 149 * 20/100 =30
- For 40% Duty cycle
- CCPR1L = 149 * 40/100 =60
Register formats:
Operation of PWM Module:
- The user has to load count in PR2 and CCPR1L registers. TMR2 register is initialized with value 0.
- The CCPR1L is loaded into CCPR1H and the CCP1 (RC2) pin goes high to start the beginning of the period.
- Then timer 2 is turned ON, count in TMR2 is incremented by 1 after each clock cycle.
- The TMR2 value is compared with CCPR1H value first and when it becomes equal The CCP pin is forced to low. That ends the duty cycle portion of the period.
- TMR2 keeps counting and now it is compared with PR2. At this point, CCP pin goes high indicating the end of one period and the beginning of the next one. Timer 2 flag bit is also set to 1
- TMR 2 is again initialized to 0, CCPR1L is loaded into CCPR1H and process continues for the next round.
Program to control speed of DC motor using PWM
/* Program to control speed of DC motor using PWM*/
#include<P18f4550.h>
void main(void)
{
TRISCbits.TRISC2 = 0; //Configure CCP1 pin as output (RC2)
CCP1CON = 0b00001100; //Select PWM mode and decimal value of Duty cycle
CCPR1L = 20; //Duty cycle (Higher 8 bits out of 10 bits) change it to vary speed
T2CON = 0b00000010; //Select Pre-scalar = 16 in Timer2
PR2 = 150; //Period Register (according to frequency of PWM)
while(1)
{
TMR2IF=0; // Clear TMR2IF
TMR2=0; //Clear Timer2
TMR2ON = 1; //Turn ON Timer2
while(TMR2IF==0); // Monitor TMR2IF
}