How to Program CCP1 Module in PIC16F877A (Compare Mode)

The following code demonstrate how to use CCP1 module in compare mode configuration. CCPR1 register value is constantly compared against the TMR1 register pair value, When both values are equal the PIR1.CCP1IF flag is set. In this example 50 KHz clock is generated on RC2/CCP1 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-11 20_36_36
Picture 2017-12-11 20_23_26

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 CCP1_dir at TRISC.B2;
sbit CCP1_CLK at PORTC.B2;
// function pro-type
void CompareModeConfig(void);
void T1Config(void);
void main(void)
{
// Compare Mode configration
CompareModeConfig();
// timer-1 configration
T1Config();
while(1)
{
while(PIR1.CCP1IF == 0); // when compare occure
PIR1.CCP1IF = 0; // clear CCP Interrupt Flag bit
// bit invert after 10uSec
CCP1_CLK = ~CCP1_CLK;
}
}
void CompareModeConfig(void)
{
// CCP1M3:CCP1M0
// 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);
// CCP1 resets TMR1
CCP1CON.CCP1M3 = 1; // ———————-
CCP1CON.CCP1M2 = 0; // Compare mode, trigger special event
CCP1CON.CCP1M1 = 1; //
CCP1CON.CCP1M0 = 1; // ———————-
PIR1.CCP1IF = 0; // clear CCP Interrupt Flag bit
CCP1_dir = 0; // set output direction
CCP1_CLK = 0; // init at 0
CCPR1H = 0x00;
CCPR1L = 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 = 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)