> From: Florian Bloemer > > Hi All! > > Is it possible to count and calculate a frequency of an external source > (about 30kHz) using the TMR0 of a Pic16c84 running at 4 MHz. If it is > possible how can this be realized on the software side. > Herr Blvmer: It certainly is posible. This is the way I would go about it: Use TMR0 in external counter mode i.e. apply the frequency to be measured to RA4/T0CKI. Assign the prescaler to TMR0 (1:256) so that more than 256 cycles of the frequency can be measured. Use instruction counting techniques to determine how many PIC cycles occur in the time that it takes for TMR0 to overflow from 255 to 0. You can capture the counter overflow event by using the 16C84's interrupt facility. Initialisation code: bcf intcon,TMR0IE ; Disable counter interrupts clrf lowbyte ; Clear time counter (24-bit) clrf medbyte clrf highbyte clrf tmr0 ; Clear counter + prescaler bcf intcon,TMR0IF ; Clear previous interrupt flag bsf intcon,TMR0IE ; Enable counter interrupts Code to increment a 24-bit counter at a constant rate is given here. Each increment of the 24-bit counter takes 9 PIC cycles (9us at 4MHz). x1 bcf intcon,GIE ; Disable interrupts incfsz lowbyte goto x2 incfsz medbyte goto x3 incf highbyte x3 bsf intcon,GIE ; Reenable interrupts goto x1 x2 goto x3 Note that interrupts are disabled around the counter increment so that the increment appears as an 'atomic' operation. This works in spite of the Microchip caveat regarding clearing of the GIE flag. The interrupt routine does most of the real work: when TMR0 overflows, it is known that 256 times prescaler cycles of input have occurred. Also, the 24-bit counter is captured at this time so it is known how many PIC cycles have occurred in the same time. A calculation can be made to determine the average input frequency over the sampling period. The calculation is f = 256 P / (0.000009 C) where f is frequency (Hz) P = prescaler (2, 4, 8, ... 256) as selected C = 24-bit count. The max frequency you could count would be about 50MHz. At this frequency, the maximum count would be about 145 hence an accuracy of better than 1%. At 30KHz, the potential accuracy would exceed your xtal's accuracy. For further information, read Microchip's data sheet cover-to-cover. Regards, SJH Canberra, Australia