# FFT based frequency calculation (algorithm)

Determining the frequency of a sinusoidal waveform can be achieved using an FFT based method. If we restrain ourselves to the simple case where the waveform is made of one single sine wave, then the fundamental frequency (f0) is indeed what we call the “waveform frequency”.

If that is the case, a simple FFT would allow isolating the frequency peaks. An histogram would then detect the highest one: the fundamental frequency. Again, this is valid only for this kind of waveforms. We can even tolerate some level of harmonics which are due to distortions.

Although this sounds like a very restrictive case, this is commonly used in device manufacturing, in order to validate a Device audio path. For that purpose, a single sine wave is injected, the device is put in loopback mode and replays the incoming wave. If the audio path is valid, then the replayed waveform should be nearly identical to the incoming one.

I had to improve the manufacturing process for a wearable device, where the audio path was tested “manually”. The operator was injecting a pre-defined audio waveform (5 second 1 Khz 16 bit mono PCM), sampling the replayed wave and visually comparing both, using Audacity. As the process is prone to operators errors, an automatic process should be used instead.

I first defined what “identical waveform” means. After some discussions, we concluded that if the following 2 criteria are met:

1. Same fundamental frequency (to within 1-2%)
2. Very low THD (Total Harmonic Distortion)

then we can conclude the waveforms are “identical enough”.

As the THD definition is subject to large discussions and interpretations, we also wanted that the THD calculation be optional. And lastly, as this tool needed to be used in a manufacturing process, a simple command line with very simple and easy to parse output was more than enough. Following Unix philosophy, tools output are designed to be input to some other tools, and manufacturing very much exploits this paradigm.

Next article will describe the implementation of the tool, using open  source libraries, libsndfile for wav file parsing and lib FFTW for Fourier calculation.