Frequency Measurement using PIC16f887

Discussion in 'Embedded Systems and Microcontrollers' started by The_Fleertz, Apr 27, 2012.

  1. The_Fleertz

    Thread Starter New Member

    Apr 23, 2012
    8
    0
    Hey guys,
    So I'm just trying to understand the capture module on the PIC16f887. I have some code which attempts to capture an 82.4 Hz frequency (this is going to be adapted later for a guitar tuner) and if the frequency captured is within 5 cents of that value it should set portb to 82 just for visual confirmation that it is working. My input to the CCP1 pin is a square wave from 0 to 6 volts at 82.4 Hz.

    All I know is that it isn't working, however, the capture module has been working for other programs I've written so that isn't the issue.

    Thanks for the help!

    Code ( (Unknown Language)):
    1.  
    2. #define  _LEGACY_HEADERS
    3.  
    4. #include <htc.h>
    5.  
    6. __CONFIG(INTIO & WDTDIS & PWRTDIS & BORDIS & BORDIS & LVPDIS & DEBUGEN & DUNPROTECT & UNPROTECT);
    7.  
    8. #define first_time  0
    9. volatile int capreg_new, capreg_old,tau;
    10. volatile char time=0;
    11.  
    12. void main(){
    13.     ANSEL=0;                    //This and next line initialize PORTB to digital
    14.     ANSELH=0;                   //
    15.     PORTB=0;
    16.     TRISB=0b00000000;           //PORTB all outputs for lights
    17.     TRISC=0b11111111;           //PORTC inputs for CCP
    18. //  CCP1CON=0b00000101; //Capture initialize
    19.     T1CON=0x01;             //Timer on
    20.     PEIE=1;                     //Enable peripheral interrupts
    21.     GIE=1;                      //Enable Global interrupts
    22.     CCP1IF=0;
    23.     CCP1IE=1;                   //Need this?
    24.    
    25.     while(1) {
    26.         CCP1IE=1;
    27.         CCP1CON=0b00000111; //Capture initialize
    28.     }  
    29. }
    30. //*********** Interrupt Service Routine *************//
    31. void interrupt isr(void){
    32.    
    33.     if(CCP1IF==1){
    34.         CCP1IE=0;           //Turn off interrupt so it doesn't stick in isr
    35.         if(first_time == time){
    36.             CCP1CON=0x00;
    37.             capreg_old=CCPR1H;
    38.             capreg_old=capreg_old<<8|CCPR1L;
    39.         }
    40.            
    41.     //  PORTB=PORTB++;
    42.         if(first_time != time){
    43.             CCP1CON=0x00;
    44.             capreg_new=CCPR1H;
    45.             capreg_new=capreg_new<<8|CCPR1L;
    46.             tau=capreg_new-capreg_old;
    47.                 if(tau>12000 && tau<12271)      PORTB=82;
    48.             capreg_old=capreg_new;
    49.         }
    50.         time=1;
    51.         CCP1IF=0;
    52.     }
    53. }
    54.  
     
Loading...