PWM Setup

PWM Period = [(PR2) + 1] x 4 x TOSC x (TMR2 Prescale Value)

PWM Duty Cycle = (CCPR4L:CCP4CON<5:4>) x TOSC x (TMR2 Prescale Value)

 

So your PWM period is adjustable using an 8bit PR# value and a 2 bit timer prescaller value (x1, x4, x16) and is based on the instruction clock speed (4 x TOSC)

The duty cycle is 2 bits more than your PR# value as it is based on the osciallator speed (TOSC, not 4 x TOSC).

The output pin is high at the start of a new period.  When the timer value matches the CCPR#H duty cycle value, and the oscillator or timer prescaller if active matches the low 2 bits CCPR#L the pin is set low.

Example


	//-------------------------
	//----- SETUP TIMER 2 -----
	//-------------------------
	//Used for: PWM
	T2CON = 0b00000110;					//TMR2 on, 1:16 prescale, 1:1 postscale
	PR2 = 0xff;							//Sets the PWM period

	//-----------------------------
	//----- SETUP CCP1 AS PWM -----
	//-----------------------------
	CCPTMRS0 = 0b00000000;		//CCP1 uses Timer2
	CCP1CON = 0b00001100;		//PWM mode, bits 5:4 are low 2 bits of 10bit PWM duty cycle

	//Set PWM duty cycle
	CCP1CONbits.DC1B = 0;		//Bits 1:0
	CCPR1L = 64;				//Bits 9:2

 

 

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *