I have some code that I am trying to get working and would like some help...
It's basically a frequency counter. I want to be able to read low frequencies (0 - ~50Hz) input on CCP1 pin, <C.2>. I have a CCP interrupt counting pulses on C.2 and I am using timer 0 (8 bit) counting up and overflowing, incrementing a tally. When the tally gets to a number corresponding to 1 second, HERTZ is updated with the number of pulses (REV) counted. Everything is zeroed and the 1 second cycle starts again. Is it output to a GLCD and refreshed every 50ms.
I am using a PIC16F877, 8Mhz external clock and an EasyPic4 development board.
All I'm getting is 0 as the HERTZ output, the timer 0 doesn;t seem to be counting and hence tally doesn't get updated, hence HERTZ never gets to see REV. At the moment I am just pressing the button on the development board to simulate a typical frequency of 2-5 hertz.
Any suggestions?
Code: Select all
Program frequency_counter
'=============================================================
DIM
REV as Byte ' total pulse counts
HERTZ as Byte
RPMStr as String[5]
Tally as integer
'=============================================================
Sub Procedure INTERRUPT()
If PIR1.CCP1IF = 1 Then ' input pulse counter, ignore CCPR1
REV = REV + 1 ' accumulate pulses
PIR1.CCP1IF = 0 ' prepare for next CCP interrupt
End If
If INTCON.T0IF = 1 Then 'test overflow, 256 bits
Tally = Tally + 1 'increment tally
INTCON.T0IF = 0 ' set T0IE, clear T0IF
TMR0 = 0
if tally = 31250 Then 'test for 1 second, (1 / (1/8Mhz * 256))
HERTZ = REV
REV = 0
tally = 0
end if
end if
End sub
'=============================================================
Sub Procedure CCP_SETUP()
TRISC.2 = 1 ' CCP1 pin is input
PIE1.CCP1IE = 1 ' enable CCP1 Interrupt
PIR1.CCP1IF = 0 ' Clear CCP1 INTERRUPT Flag
INTCON = 11100000 ' enable TMRO interrupt
OPTION_REG.T0CS = 1 ' bit 5 TMR0 Clock Source Select bit:0=Internal Clock (CLKO) / 1=Transition on T0CKI pin
OPTION_REG.T0SE = 0 ' bit 4 TMR0 Source Edge Select bit: 0=low/high / 1=high/low
OPTION_REG.PSA = 1 ' bit 3 Prescaler Assignment bit: 0=Prescaler is assigned to the Timer0
OPTION_REG.PS2 = 0 ' bits 2-0 PS2:PS0: Prescaler Rate Select bits
OPTION_REG.PS1 = 0
OPTION_REG.PS0 = 0
TMR0 = 0 ' preset for timer register
end sub
'=============================================================
Sub Procedure GENERAL_INIT()
ADCON1 = 0 ' disable analogs
TRISA = 0
TRISB = 0
TRISC = 1
TRISD = 0
end sub
'=============================================================
Main:
General_Init()
CCP_Setup()
Glcd_Init(PORTB, 0, 1, 2, 3, 5, 4, PORTD)
Glcd_Fill(0xAA)
Glcd_Fill(0x00)
Glcd_Set_Font(@SYSTEM3x6, 3, 6, 32)
REV = 0
HERTZ = 0
while TRUE
Delay_ms(50) ' update LCD every 50ms
WordToStr(HERTZ, RPMStr) ' convert for LCD
glcd_write_text("RPM",20,0,1)
glcd_write_text(RPMStr,65,1,1)
wend
end.