#include<pic.h>
#include<htc.h>
#define __PIC16F877AH
#define _XTAL_FREQ 2000000
__CONFIG(PWRTE_ON & FOSC_HS & LVP_OFF & WDTE_OFF);
unsigned int a=0;
void InitPWM(void);
void SetPWMDutyCycle(unsigned int l);
void delay(unsigned int i)
{
while(i--);
}
void InitPWM(void)
{
TRISC2 = 0; // Make CCP1 pin as output
CCP1CON = 0x0C; // Configure CCP1 module in PWM mode
PR2 = 0xFF; // Configure the Timer2 period
T2CON = 0x01; // Set Prescaler to be 4, hence PWM frequency is set to 4.88KHz.
SetPWMDutyCycle(0); // Intialize the PWM to 0 duty cycle
T2CON |= 0x04; // Enable the Timer2, hence enable the PWM.
}
void SetPWMDutyCycle(unsigned int l) // Give a value in between 0 and 1024 for DutyCycle
{
CCPR1L = l>>2; // Put MSB 8 bits in CCPR1L
CCP1CON &= 0xCF; // Make bit4 and 5 zero
CCP1CON |= (0x30&(l<<4)); // Assign Last 2 LSBs to CCP1CON
}
void main(void)
{
InitPWM();
while(1)
{
SetPWMDutyCycle(a); //50% duty cycle
a++;
if(a>1000)
a=0;
}
}
No comments:
Post a Comment