unsigned int t=0;
int cnt=0;
void interrupt() {
if(CCP1IF_bit == 1) { // Rising edge
CCP1IF_bit = 0; //reset capture interrupt flag
cnt++;
if(cnt == 1) // first rising edge is detected
{
TMR1ON_bit = 1; //timer1 start counting
}
if(cnt == 2) //second rising edge is detected
{
TMR1ON_bit = 0; //stop timer1
t = (CCPR1H<<8) + CCPR1L; // Store the current value of Timer1
CCPR1L=0; //Reset timer
CCPR1H=0;
PIE1.CCP1IE = 0;
PIR1.CCP1IF = 0; //reset capture interrupt flag
PIE1.CCP1IE = 1;
cnt=0; //reset rising edge counter
}
}
if(TMR1IF_bit == 1){ // TMR1 Overflow
TMR1ON_bit = 0; //stop timer1
CCPR1L=0; //Reset timer
CCPR1H=0;
TMR1IF_bit = 0; //Reset TMR1 Overflow bit
cnt=0; //Reset riding edge counter
t = 0;
}
}
void Configure_Capture(){
//1:8 Prescaler, External CLK
T1CKPS1_bit = 1;
T1CKPS0_bit = 1;
//Capture every rising edge
CCP1M3_bit = 0;
CCP1M2_bit = 1;
CCP1M1_bit = 0;
CCP1M0_bit = 1;
CCP1IE_bit = 1; // Enable CCP1 interrupt
//enable all interrupts
PEIE_bit = 1;
GIE_bit = 1;
TRISIO = 001100; //GP0, GP1 ,GP4 ,GP5 are outputs , GP2, GP3 are inputs
//reset high & low bytes of timer1 & capture registers
TMR1H = 0; TMR1L = 0;
CCPR1H = 0; CCPR1L = 0;
TMR1ON_bit = 0;
}
void main() {
GPIO = 0;
ANSEL = 0; // All pin digital
ADCON0 = 0x00; // Disable ADC
CMCON0=0;
CMCON1=0; // Disable comparators
Configure_Capture();
do{
if(t <= 50000 && t > 0){
GPIO = 000001;
} else GPIO = 000000;
} while(1);
}