How to Program CCP2 Module in PIC16F877A (Compare Mode)

The following code demonstrate how to use CCP2 module in compare mode configuration. CCPR2 register value is constantly compared against the TMR1 register pair value, When both values are equal the PIR2.CCP2IF flag is set. In this example 50 KHz clock is generated on RC1/CCP2 pin (it may be any other pin ). 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.
Picture 2017-12-16 09_21_23

Code in mikroC

// Generate clock 50 Khz
// Tick Time (Sec) = (4 x prescalar)/Fosc
// prescalar 1:1
// Fosc = 20,000,000 Hz
// Tick Time (Sec) = 0.0000002
// direction signal
sbit CCP2_dir at TRISC.B1;
sbit CCP2_CLK at PORTC.B1;
// function pro-type
void CompareModeConfig(void);
void T1Config(void);
void main(void)
{
// Compare Mode configration
CompareModeConfig();
// timer-1 configration
T1Config();
while(1)
{
while(PIR2.CCP2IF == 0); // when compare occure
PIR2.CCP2IF = 0; // clear CCP Interrupt Flag bit
// bit invert after 10uSec
CCP2_CLK = ~CCP2_CLK;
}
}
void CompareModeConfig(void)
{
// CCP2M3:CCP2M0
// 1000 = Compare mode, set output on match (CCPxIF bit is set)
// 1001 = Compare mode, clear output on match (CCPxIF bit is set)
// 1010 = Compare mode, generate software interrupt on match
// (CCPxIF bit is set, CCPx pin is unaffected)
// 1011 = Compare mode, trigger special event
// (CCPxIF bit is set, CCPx pin is unaffected);
// CCP2 resets TMR1
CCP2CON.CCP2M3 = 1; // ———————-
CCP2CON.CCP2M2 = 0; // Compare mode, trigger special event
CCP2CON.CCP2M1 = 1; //
CCP2CON.CCP2M0 = 1; // ———————-
PIR2.CCP2IF = 0; // clear CCP Interrupt Flag bit
CCP2_dir = 0; // set output direction
CCP2_CLK = 0; // init at 0
CCPR2H = 0x00;
CCPR2L = 0x32;
}
void T1Config(void)
{
TMR1H = 0x00; // clear higher byte
TMR1L = 0x00; // clear lower byte
// T1CKPS1:T1CKPS0
// 11 = 1:8 prescale value
// 10 = 1:4 prescale value
// 01 = 1:2 prescale value
// 00 = 1:1 prescale value
T1CON.T1CKPS1 = 0; // 1:1 prescale value
T1CON.T1CKPS0 = 0; // 1:1 prescale value
T1CON.T1OSCEN = 0; // Oscillator is disabled
T1CON.T1SYNC = 0; // This bit is ignored
T1CON.TMR1CS = 0; // Internal clock (FOSC/4)
T1CON.TMR1ON = 1; // Enables Timer1
}

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)