Measuring a frequency is pretty straight forward, and can be done on just about
any PIC with a spare input pin.
Here are a few ideas.
1. Use the COUNT command.
2. Use TIMER1.
3. Use the hardware capture module.
And here's a simple test program using all 3 options. Tested on a 16F627A.
An 8-pin PIC was used for the frequency generator.Code:@ DEVICE MCLR_OFF, INTRC_OSC, WDT_OFF, LVP_OFF, BOD_ON, PWRT_ON, PROTECT_OFF DEFINE OSC 4 T1 VAR WORD T2 VAR WORD TRISB = %00001000 ' RB3 = input T1CON = 0 TMR1L=0 TMR1H=0 ' GOTO Test3 ' using COUNT ' GOTO Test2 ' using capture ' GOTO Test1 ' using TMR1 with pin state watch Test1: WHILE PORTB.3=1 ' noise filter WEND WHILE PORTB.3=0 ' wait for low to high edge WEND T1CON=1 ' start TMR1 on rising edge WHILE PORTB.3=1 ' wait for high to low edge WEND WHILE PORTB.3=0 ' wait for 2nd rising edge (end of period) WEND T1CON=0 ' stop TMR1 ' Record the period as T1. T1.HighByte = TMR1H T1.LowByte = TMR1L HSEROUT ["Period = ",DEC T1,13,10] PAUSE 10000 TMR1L=0 TMR1H=0 GOTO Test1 ' Serial from PIC ' Shown on O-Scope ' Period = 3143 ' 315 Hz ' Period = 2403 ' 412 Hz ' Period = 2113 ' 468 Hz ' Period = 1643 ' 603 Hz Test2: 'Configure capture for rising edge. CCP1CON = %00000101 ' Capture mode, capture on rising edge 'Setup & start Timer1. T1CON = 1 ' TMR1 prescale=1, clock=Fosc/4, TMR1=on. Loop: 'Wait for the capture flag bit to be set. WHILE PIR1.2 = 0 WEND 'Record the first capture value as T1. T1.HighByte = CCPR1H T1.LowByte = CCPR1L 'Clear the capture flag. PIR1.2 = 0 'Wait for the capture flag to be set a 2nd time. WHILE PIR1.2 = 0 WEND 'Record the 2nd capture value as T2. T2.HighByte = CCPR1H T2.LowByte = CCPR1L 'Clear the capture flag PIR1.2 = 0 'T2-T1 = the period in uS. HSEROUT ["Period = ",DEC T2-T1,13,10] PAUSE 1000 GOTO Loop ' Serial from PIC ' Shown on O-Scope ' Period = 3149 ' Freq = 315 Hz ' Period = 2410 ' Freq = 412 Hz ' Period = 2120 ' Freq = 468 Hz ' Period = 1648 ' Freq = 603 Hz Test3: COUNT PORTB.3,20,T1 'Count low to high transitions for 20mS HSEROUT ["Count = ",DEC T1,13,10] PAUSE 10000 GOTO Test3 ' Serial from PIC ' Shown on O-Scope ' Count = 6 ' 315 Hz ' Count = 8 ' 412 Hz ' Count = 9 ' 468 Hz ' Count = 12 ' 603 Hz ' Resolution with COUNT isn't that great, but it works. ' 20mS/count value = the approximate period. END
Capture could be used with the capture flag generating an interrupt if
you prefer not to wait for state changes.
I'm sure there are several more ways to do this, but this should get you
started.




Bookmarks