Toll-Free Customer Support 24/7

PIC Development Board

/*
* Project name:PWM(Pulse Width Modulation)
PIC Development Board
* Copyright
(c) Researchdesignlab.com
* Test configuration:
MCU: PIC16F877A
Dev.Board: PIC
Oscillator: 20.0 MHz
Software: MPLAB IDE v8.92(HI-TECH_C)
*/

 

#include<htc.h>
#define XTAL 20000 //20Mhz=20000Khz
#define PWM_Freq 1 //1Khz PWM frequency
#define TMR2_PRE 16 //Timer2 Prescale
#define PR2_Val ((char)((XTAL/(4*TMR2_PRE*PWM_Freq))-1))
//Calculation for Period register PR2 (2Khz)

#define Duty_Cyc PR2_Val*2

unsigned int i;

void PWM_init(void);
void PWM_change(unsigned int);
void DelayMs(unsigned int);
void main(void)
{
PWM_init();
while(1)
{
i=0;
PWM_change(i);
DelayMs(10);
while(i<PR2_Val)
{
i=i+1;
PWM_change(i);
DelayMs(200);
}
}
}

void PWM_init(void)
{
TRISC2=0; //PWM channel 1 and 2 configured as output
TRISC1=0;
PORTC = 0x00;
CCP1CON=0x0c; //CCP1 and CCP2 are configured for PWM
CCP2CON=0x0c;
PR2=PR2_Val; //Move the PR2 value

T2CON=0x03; //Timer2 Prescale is 16
TMR2=0x00;
TMR2ON=1; //Turn ON timer2
}

void PWM_change(unsigned int DTY) //Duty cycle change routine
{
CCPR1L=DTY; //Value is between 0 to 255
CCPR2L=DTY;
}

void DelayMs(unsigned int Ms) //Delay Routine
{
int delay_cnst;

while(Ms>0)
{
Ms--;

for(delay_cnst = 0;delay_cnst <220;delay_cnst++);
//delay constant for 1Ms @20Mhz
}
}

Back to top