Generate PWM with Pic controller
Pulse width modulation (PWM) is a technique to controls the pulse signals for power transmission applications like motor controlling, LED dimming and many more. Pulse modulation technique has some little calculations and some parameters.
- · Duty cycle: - Duty cycle describe On time of a pulse.
- · Period: - Total time of a pulse On time + Off time
- · Frequency: - How many periods come in a second is frequency.
Example :-
Frequency = 2Khz
Period = 1 / frequency = 1 / 2000 = 0.0005s
= 5ms
Duty Cycle = (OnTime / Period) * 100%
Pic18f series controllers have standard CCP module with Enhanced PWM capabilities. These include the provision for 2 or 4 output channels, user-selectable polarity and automatic shutdown and restart. PWM module uses timer2 in free running clock mode to derive a reference clock. We will discuss only on a single PWM.
Block Diagram
Control registers of PWM
- · CCPxCON
- · PR2
- · CCPRxL
- · CCPRxH
- · T2CON
CCPxCON: CCPx CONTROL REGISTER (28-PIN DEVICES)
Bit7-6 :- Not in use
Bit5-4 :- PWM Duty Cycle bit 1 and bit 0 for CCPx Module
- PWM duty cycle can be use as 10 bit resolution mode. These bits are LSB bits 0 & 1. Other 8 MSb are containing with CCPRxL register. The following formula uses to calculate the PWM duty cycle in time.
PWM Duty Cycle = (CCPRxL:CCPxCON) • TOSC • (TMR2 Prescale Value)
In PWM mode, CCPRxH is a read-only register.
Bit3-0 :- CCP mode selection
- CCP module can be configured as variant types of modes that are given in datasheet CCPxCON register. Now we are talking about PWM only so we will chose only last mode.
CCP1CONbits.CCP1M3 = 1; //Selecting PWM mode
CCP1CONbits.CCP1M2 = 1;
Other 2 bits can be set or not.
PWM Output
See the Timer2 register: - http://embeddedooo.blogspot.in/2017/02/timer1-timer2-timer3.html
Codes:-
#include <p18f2520.h>
void config_timer2(void);
void config_PWM_ccp1(void);
void main()
{
TRISC=0x00; // Set PORTC as output.
PORTC=0x00;
config_PWM_ccp1();
config_timer2();
while(1)
{
CCPR1L=127; // PWM duty cycle % = PR2/CCPR1L
}
}
void config_timer2()
{
// Timer2 Registers:
// Prescaler=1:1; TMR2 PostScaler=1:11; PR2=227 - Freq = 2,002.40288Hz - Period = 0.4994 ms
T2CONbits.T2OUTPS3 = 1; // Postscaler selection bits
T2CONbits.T2OUTPS2 = 0;
T2CONbits.T2OUTPS1 = 1;
T2CONbits.T2OUTPS0 = 0;
T2CONbits.TMR2ON = 1; // Timer2 on bit: 1=Timer2 is on;
T2CONbits.T2CKPS1 = 0; // bits 1-0 Prescaler Rate Select bits
T2CONbits.T2CKPS0 = 0;
PR2 = 227; // PR2 (Timer2 Match value)
}
void config_PWM_ccp1()
{
CCPR1L=0; // Set duty cycle register value to 0.
CCP1CONbits.CCP1M3 = 1; //Selecting PWM mode
CCP1CONbits.CCP1M2 = 1;
CCP1CONbits.CCP1M1 = 0;
CCP1CONbits.CCP1M0 = 0;
}
Download project files:-
https://drive.google.com/file/d/0B886Kbl42IVuWFZMbTJYSW01clk/view?usp=sharing
https://drive.google.com/file/d/0B886Kbl42IVuWFZMbTJYSW01clk/view?usp=sharing
No comments:
Post a Comment