If RC2 is avilable you could also use the hardware capture module.
Code:
' Measuring pulse width with capture module
' Input signal connected to RC2/CCP1 pin
DEFINE OSC 4
Symbol Capture = PIR1.2 ' CCP1 capture flag
T1 VAR WORD ' 1st capture value
T2 VAR WORD ' 2nd capture value
T3 VAR WORD ' 3rd capture value
LowCycle VAR WORD ' low pulse width rsult
HighCycle VAR WORD ' high pulse width result
TRISC.2 = 1 ' CCP1 input pin (Capture input)
INTCON = 0 ' Interrupts off
CCP1CON = %00000101 ' Capture mode, capture on rising edge
T1CON = %10000001 ' TMR1 prescale=1, clock=Fosc/4, TMR1=on
Main:
WHILE !Capture ' wait for rising edge capture
WEND
' Rising edge detected so record timer1 value
T1.HighByte = CCPR1H : T1.LowByte = CCPR1L
Capture = 0 ' Clear capture flag bit
CCP1CON.0 = 0 ' Configure capture for falling edge now
While !Capture ' While here for capture on falling edge
Wend
' Falling edge detected so record timer1 value again
T2.HighByte = CCPR1H : T2.LowByte = CCPR1L
Capture = 0 ' Clear capture flag bit
CCP1CON.0 = 1 ' Configure capture for rising edge now
While !Capture ' While here for capture on falling edge
Wend
' Falling edge detected so record timer1 value again
T3.HighByte = CCPR1H : T3.LowByte = CCPR1L
CCP1CON = 0 ' disable capture during data processing
HighCycle = T2-T1 ' High pulse width = T2 - T1
LowCycle = T3-T2 ' Low pulse width = T3 - T2
HSEROUT ["High pulse width = ",DEC HighCycle,"uS",13,10]
HSEROUT ["Low pulse width = ",DEC LowCycle,"uS",13,10]
HSEROUT ["Period = ",DEC LowCycle+HighCycle,"uS",13,10]
Capture = 0 ' Clear capture flag bit
CCP1CON = %00000101 ' Capture mode, capture on rising edge
GOTO Main
END
If the measured frequency is too slow you can use the timer prescaler. You
want the frequency to be high enough so the timer doesn't overflow during
the measurement period.
Bookmarks