PWM Library

oad

PWM: (Page # 48)

These functions can be used to work with the PWM units built in the CCP and ECCP modules, the functions having EPWM in their syntax can only be used with devices where Enhanced Capture Compare PWM module is implemented using a ECCPxCON register. The PWM library consists of the following functions:

OpenPWMx(arguments)/ OpenEPWMx(arguments):

Configures the frequency of the PWMx channel.

SetDCPWMx(arguments)/ SetDCEPWMx(arguments):

Writes a new duty cycle value in the specified PWM duty cycle registers.

SetOutputPWMx(arguments)/ SetOutputEPWMx(arguments):

Sets the configuration bits for the ECCP register. Sets the type of PWM output (mode).

ClosePWMx()/CloseEPWMx():

Closes the specified PWM Channel.

Here is the code:

Code

//This is a program that shows the use of PWM Module with

//Microchips Libraries.

//The PWM Section is documented on P#48 of C18 Libraries

//Use 181320Basic.DSN

// It has a duty cycle of nearly 50%

// The motor Runs at an RPM of 60 Revolutions(It does take some time to stabilize)

/****************************************************************/

// Following are the cauculations for the PWM Period and Duty Cycle

//Refer to Page 121 of the data sheet.

//This has been done for an arbitary PWM freq, calculate PR2 for desired freq

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

// =[250+1]*(1/4Mhz)*(1)

// =251*0.25us

// PWM Period =62.75us

// PWM Frequency=1/62.75us

// PWM Frequency=15.936Khz

/****************************************************************/

/****************************************************************/

// For PWM Duty Cycle:

// (CCPR1L:CCP1CON<5:4>)= PR2*Desired Duty Cycle

// = 250*50

// = 125

// =0b111110100

// By experimentally Checking for overhead using MPLabs Logic Analyzer

// the value (CCPR1L:CCP1CON<5:4>) is found to be 0b111110101

/****************************************************************/

#include<p18f1320.h>// Include files and definitions for the Processor

#include<pwm.h>// Include function definitions for the PWM library

#include<timers.h>// Include function definitions for the Timer library

#pragma config LVP=OFF,OSC=INTIO2,WDT=OFF// Configuration settings for the 18f1320.

void main(void)

{

OSCCON=0x60;//Internal 4MHZ Oscillator

ADCON1=0X7F;//Make all ports Digital

OpenTimer2( TIMER_INT_OFF &//Use Timer 2, turn its interrupt off, prescaler of 1:1 (no prescaler)

T2_PS_1_1);

OpenPWM1(250);// Total PWM cycle will consist of 250 cycles.(PR2 value)

SetDCPWM1(0b111110101);// Set PWM Duty Cycle by (CCPR1L:CCP1CON<5:4>) value

while(1);// Wait here

}

The duty cycle of the PWM output is nearly 50 percent:

The Code for the PWM function can also be downloaded from:

http://www.box.net/shared/rfpgt3rj56