MEL PICBASIC Forum - Using hardware capture


  • Using hardware capture

    Got a PIC with hardware capture, and looking for a way to record high & low pulse widths
    with better resolution than PULSIN?

    Here's how .. with an example from the Microchip CCP & ECCP Tips & Tricks modified to
    work with PBP.
    Code:
    ' Measuring signal pulse widths with capture module
    
    ' Procedure for high-going pulse:
    ' 1. Configure CCP to capture on rising edge
    ' 2. Setup Timer1 so it will not overflow during max pulse width time
    ' 3. Enable ccp capture
    ' 4. Once capture flag bit is set, save captured value as T1
    ' 5. Reconfigure CCP to capture on falling edge
    ' 6. On 2nd capture, save 2nd value as PW
    ' 7. Subtract T1 from PW for the pulse width value
    
        DEFINE OSC 4
    
        Symbol    Capture = PIR1.2 ' CCP1 capture flag
        T1        VAR WORD         ' 1st capture value
        PW        VAR WORD         ' 2nd capture value & ultimately final pulse width
    
        TRISC.2 = 1          ' CCP1 input pin (Capture input on 18F242)
        INTCON = 0           ' Interrupts off
        
    ReLoad:
        CCP1CON = %00000101  ' Capture mode, capture on rising edge
        T1CON = 0            ' TMR1 prescale=1, clock=Fosc/4, TMR1=off
        TMR1H = 0            ' Clear high byte of TMR1 counter
        TMR1L = 0            ' Clear low byte
        T1CON.0 = 1          ' Turn TMR1 on here
    
        Capture = 0         ' Clear capture int flag bit
        While !Capture      ' Wait here until capture on rising edge
        Wend
        
        ' Rising edge detected / stuff 'captured' Timer1 value in T1
        T1.HighByte = CCPR1H
        T1.LowByte = CCPR1L
        
        CCP1CON.0 = 0       ' Configure capture for falling edge now
        Capture = 0         ' Clear capture interrupt flag bit
        
        While !Capture      ' Wait here until capture on falling edge
        Wend
        
        ' Falling edge detected / stuff 'captured' Timer1 value in PW
        PW.HighByte = CCPR1H
        PW.LowByte = CCPR1L
        
        PW = PW-T1           ' High pulse width = PW-T1
    
        HSEROUT [DEC PW,"uS High",13,10]    ' Output to RS232 display
        GOTO ReLoad
        
        END
    If you need to measure the width of a low-going pulse , just change it to capture
    the falling edge first with CCP1CON = %00000100, and rising edge next with
    CCP1CON.0 = 1.

    Real simple ... real effective ... and spot-on timing. Even works on tiny little PICs
    like the 12F683 12F615, etc...;o)
    This article was originally published in forum thread: Using hardware capture started by Bruce View original post