# How to measure frequency of sine wave?

How to measure frequency of sine wave using pic microcontroller? I found the article on this website http://microcontrollerslab.com/sine-wave-frequency-measurement-using-pic/ But I didn't understand code. Anyone can help me to understand code on this website?

• You need to tell us a little more about your application. What frequency is the signal? What voltage range? How are you sampling it, and what are your requirements for accuracy etc? – Nick Johnson May 20 '15 at 10:31
• I've looked at the code, it seems to me it won't work well but I might be wrong. What part is not clear to you? – Vladimir Cravero May 20 '15 at 10:36
• Might I recommend 2 measurements within 1 microsecond to approximate the gradient? The frequency is just the time between sign changes in the gradient. It'd be rather more accurate. – Dr Coconut May 20 '15 at 11:20
• You need to tell us which part of it you don't understand. The diagram and the code are fairly clear if you understand the language, the circuitry, and the system. – JRE May 20 '15 at 11:57

This is the key element of the frequency measurement code:

TMR0=0; // clear TMR0
Delay_ms(1000); // Delay 1 Sec
...
Display_Freq(TMR0/2); // divide by 2


The author is using the TMR0 timer/counter to count the zero-crossing events of the input signal. (The article uses a transformer to step down 220VACrms 50Hz mains line frequency to 9VACrms, then uses a full bridge rectifier and a resistive divider to generate the zero-crossing event signal. I'm not sure how they intended to test this circuit.)

After running the counter for 1 second, the value in the counter is equal to double the frequency, because each full-wave rectified cycle has two pulses.

The rest of the code in Display_Freq(f) is just user interface code, to convert the numerical frequency into characters to display on the LCD.

• This answer is good but I don't like the design. There's no 'anti bounce', and if used as a periodmeter that 'zero crossing detection' circuit will show what it's really worth. Dr Coconut suggestion above, implement a gradient change detector, guarantees much more precision. The ADC is needed of course but it does not seem to me that the micro is doing anything. – Vladimir Cravero May 20 '15 at 12:14