How to Program CCP1 Module in PIC16F877A (10-Bit PWM Mode)

The following code demonstrate how to use CCP1 module in PWM mode with 10-bit of resolution. On initialization PWM duty cycle is set to zero, when "DUTY INCREASE" button is pressed pulse width start increasing and by pressing "DUTY DECREASE" button, pulse width start decreasing. The code is written in “mikroC PRO for PIC v.6.6.3” IDE and simulation is done with Proteus 8.0 SP0. At the end of code, you can find complete project files for download.




 Code in mikroC

// define crystal frequency
#define _XTAL_FREQ 20000000
// timer-2 prescalar
#define TMR2_PRESCALE 4
sbit DUTY_INC_Dir at TRISB.B0;
sbit DUTY_DEC_Dir at TRISB.B1;
sbit DUTY_INC at PORTB.B0;
sbit DUTY_DEC at PORTB.B1;
long pwm_freq = 5000;
PWM1_Initialize(void);
PWM1_Duty(unsigned int duty);
void main(void)
{
unsigned int count = 0;
// make as input
DUTY_INC_Dir = 1;
DUTY_DEC_Dir = 1;
// init pwm1
PWM1_Initialize();
PWM1_Duty(0);
while(1)
{
if(DUTY_INC == 1)
{
PWM1_Duty(count);
if(count>=1023)
count = 0;
else
count++;
Delay_ms(20);
}
if(DUTY_DEC == 1)
{
PWM1_Duty(count);
if(count<= 0)
count = 1023;
else
count--;
Delay_ms(20);
}
}
}

PWM1_Initialize(void)
{
// set pwm1 frequency
PR2 = (_XTAL_FREQ/(pwm_freq*4*TMR2_PRESCALE)) - 1;
// Configure the CCP1 module in pwm mode
CCP1CON.CCP1M3 = 1;
CCP1CON.CCP1M2 = 1;
CCP1CON.CCP1M1 = 0;
CCP1CON.CCP1M0 = 0;
// set timer-2 prescalar is 4
T2CON.T2CKPS1 = 0;
T2CON.T2CKPS0 = 1;
// turn timer-2 ON
T2CON.TMR2ON = 1;
// make RC2/CCP1 as output
TRISC.B2 = 0;
}
PWM1_Duty(unsigned int duty)
{
if(duty<1023)
{
duty = ((float)duty/1023)*(_XTAL_FREQ/(pwm_freq*TMR2_PRESCALE));
// These bits are the two LSbs of the PWM duty cycle
// store bit-0
CCP1CON.CCP1X = duty & 1;
// store bit-1
CCP1CON.CCP1Y = duty & 2;
// store bit-9 to bit-2, by shifting two bits right
CCPR1L = duty>>2;
}
}

Download Files

For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.

Comments

Popular posts from this blog

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program Interrupts in PIC16F877A

How to Program SPI in PIC16F877A (Slave Mode)