How to Program CCP2 Module in PIC16F877A (Capture Mode)

The following code demonstrate how to use CCP2 module in capture mode configuration.  The PIR2.CCP2IF flag is set when rising edge is detected on RC1/CCP2 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 07_25_58

Code in mikroC

// 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;
// function pro-type
void SendToUART(unsigned long ccpr1);
void CaptureModeConfig(void);
void T1Config(void);
void main(void)
{
unsigned long ccpr2 = 0;
UART1_Init(115200);
// Capture Mode configration
CaptureModeConfig();
// timer-1 configration
T1Config();
while(1)
{
while(PIR2.CCP2IF == 0);
PIR2.CCP2IF = 0; // clear CCP Interrupt Flag bit
TMR1H = 0x00; // must be clear
TMR1L = 0x00; // must be clear
ccpr2 = CCPR2H; // load higher byte register
ccpr2 = ccpr2 << 8; // shift 8 bit locations to left
ccpr2 = ccpr2 | CCPR2L; // ORs higher and lower byte to combine 16-bit
SendToUART(ccpr2);
}
}
void SendToUART(unsigned long ccpr2)
{
char buffer[16] = {‘\0’};
if (UART1_Tx_Idle() == 1)
{
LongWordToStr(ccpr2,buffer);
UART1_Write_Text(“Captured Value:”);
UART1_Write_Text(buffer);
UART1_Write_Text(“\r\n”);
}
}
void CaptureModeConfig(void)
{
// CCP2M3:CCP2M0
// 0100 = Capture mode, every falling edge
// 0101 = Capture mode, every rising edge
// 0110 = Capture mode, every 4th rising edge
// 0111 = Capture mode, every 16th rising edge
CCP2CON.CCP2M3 = 0; // ———————-
CCP2CON.CCP2M2 = 1; // Capture mode, every rising edge
CCP2CON.CCP2M1 = 0; //
CCP2CON.CCP2M0 = 1; // ———————-
PIR2.CCP2IF = 0; // clear CCP Interrupt Flag bit
CCP2_dir = 1; // set input direction
CCPR2H = 0x00;
CCPR2L = 0x00;
}
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 = 1; // Oscillator is enabled
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 Interrupts in PIC16F877A

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program SPI in PIC16F877A (Slave Mode)