PIC Basic Frequency Counter

Status
Not open for further replies.

transistance

New Member
Is there a better way to sense/capture a rising edge then to create a wait loop while input is 0 then a wait loop while input is 1, and then starting a count.

Do I need to use any kind of interrupts to capture the frequency of a square wave with variable duty cycle?
 
Sure, if you want to check other sensors, do other coding, then using the capture mode and interrupts would be the way to go. Roughly speaking:

Initialize the CCP1 by:
Setting the CCP1 as an input
Set CCP1CON for rising/falling edge
Clear the PIR1 flag
Set PIE = 1
Set GIE = 1

On Interrupt;
Clear the CCPiIF flag
Check the edge for rising/falling
If rising set capture back to falling edge, start TMR1
If falling stop TMR1, Read variables for CCPR1L, and CCPR1H, set capture to rising edge
 
Keep in mind, while the counter itself is asynchronous the sampling of it is not so you may get quantization errors, depending on how far away from a system clock harmonic you are and how high the frequency is the error rate will change. However this has the positive benefit of creating at least 1 LSB of noise making it a prime candidate for taking a large number of samples and decimating them into a higher precision readings. At the very least you should average the noise out with as large a moving sample buffer as you can spare from memory and processor speed. You could get unexpected results if you try to trust individual readings are the frequency is high.
 
Last edited:
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…