Try Embedded

The FFT and frequency analysis

Bins, resolution, windows and spectral leakage, and Goertzel.

From time to frequency

A signal sampled over time can also be described as a sum of sine waves of different frequencies. The Discrete Fourier Transform (DFT) computes that frequency content from N samples, and the Fast Fourier Transform (FFT) is the efficient algorithm that makes it practical on a microcontroller.

Embedded uses: vibration analysis and predictive maintenance (a failing bearing has a characteristic frequency), audio spectrum displays and tone detection, finding the dominant frequency in a sensor signal, power-quality analysis (harmonics on a mains supply), and radar and ultrasonic signal processing.

What an FFT gives you

From N samples taken at sample rate fs:

QuantityValue
Number of frequency binsN / 2 useful ones (for a real-valued input)
Bin width (frequency resolution)fs / N
Highest frequencyfs / 2 (Nyquist)
Bin k representsFrequency k × fs / N
Each bin's outputA complex number: magnitude (how much) and phase

Resolution improves only by measuring for longer: 1 Hz resolution needs 1 second of data whatever the sample rate.

#include <stdio.h>
#include <math.h>

#define N 32

int main(void) {
  double pi = 3.14159265358979, fs = 320.0;     /* bin width = fs / N = 10 Hz */
  double x[N];
  /* A 50 Hz sine (amplitude 1.0) plus a 120 Hz sine (amplitude 0.5). */
  for (int n = 0; n < N; n++)
    x[n] = sin(2 * pi * 50 * n / fs) + 0.5 * sin(2 * pi * 120 * n / fs);

  /* A plain DFT, O(N^2): fine for showing the idea; an FFT gives the same numbers in O(N log N). */
  printf("bin  freq   magnitude\n");
  for (int k = 0; k <= N / 2; k++) {
    double re = 0, im = 0;
    for (int n = 0; n < N; n++) {
      re += x[n] * cos(2 * pi * k * n / N);
      im -= x[n] * sin(2 * pi * k * n / N);
    }
    double mag = 2.0 * sqrt(re * re + im * im) / N;   /* scale so a sine of amplitude A reads A */
    if (mag > 0.05) printf("%3d  %4.0f Hz  %.2f\n", k, k * fs / N, mag);
  }
  return 0;
}

Both tones appear in exactly the right bins with the right amplitudes, because 50 Hz and 120 Hz are exact multiples of the 10 Hz bin width. Real signals rarely are.

Why the FFT is fast

A direct DFT takes N² complex multiplications; the radix-2 FFT (Cooley-Tukey) splits the problem recursively into halves and takes about (N/2)·log₂N. For N = 1024 that is about 5,000 instead of a million. Radix-2 FFTs need N to be a power of two; pad with zeros or use a mixed-radix implementation otherwise.

On a Cortex-M4 at 100 MHz, CMSIS-DSP computes a 1024-point real FFT in Q15 or float in well under a millisecond, using the DSP and FPU instructions.

Spectral leakage and windows

The FFT assumes the N samples repeat forever. If the signal does not complete a whole number of cycles in the window, the jump at the wrap-around smears its energy into neighbouring bins: spectral leakage. A tone between two bins appears as a broad hump with a reduced peak.

The cure is to multiply the samples by a window function that tapers smoothly to zero at both ends before the FFT:

WindowMain lobeLeakage (side lobes)Use
Rectangular (no window)NarrowestWorst (−13 dB)Only for signals that fit the window exactly
HannModerateGood (−31 dB)General purpose, the usual default
HammingModerateGood near the peakAudio, speech
BlackmanWideExcellent (−58 dB)Finding weak tones next to strong ones
Flat-topVery wideGoodAccurate amplitude measurement

Windows reduce the total energy, so scale magnitudes by the window's coherent gain (0.5 for Hann) when measuring amplitudes.

Practical design

  1. Choose fs above twice the highest frequency of interest, with an analog anti-alias filter.
  2. Choose N from the resolution needed: N = fs / resolution, rounded up to a power of two.
  3. Capture N samples with a timer-triggered ADC and DMA into a buffer (double-buffered for continuous analysis).
  4. Remove the DC offset (subtract the mean), apply the window, run the FFT.
  5. Compute magnitudes (often squared magnitude to avoid the square root), and convert to dB if displaying.
  6. For continuous monitoring, overlap successive windows by 50% so events at window edges are not missed.

For detecting one known frequency (a DTMF tone, a carrier), the Goertzel algorithm computes a single DFT bin in N multiply-adds with almost no memory, much cheaper than a full FFT.

Pitfall: Forgetting to remove the DC offset of an ADC signal (for example a sensor centred on 1.65 V) puts a huge peak in bin 0 whose leakage can hide small low-frequency components. Subtract the mean, or ignore the first few bins.

Interview question: How would you detect a failing bearing from an accelerometer with an MCU?

Answer: Sample the accelerometer with a timer-triggered ADC or the sensor's FIFO at a rate well above the bearing fault frequencies (computed from shaft speed and bearing geometry), with anti-alias filtering. Collect blocks of N samples, remove the mean, apply a Hann window and run an FFT (CMSIS-DSP), possibly on the envelope of the signal for bearing faults. Compare the magnitudes in the bands around the expected fault frequencies and their harmonics against a baseline learned when the machine was healthy, averaging several spectra, and raise an alert when they grow consistently.

Build it: find the gimbal's resonance

This is step 2 of the module project, the camera gimbal. The notch in step 1 was set to 250 Hz, but every camera and lens the owner mounts changes the arm's mass and so its mechanical resonance. Good gimbals find it themselves: at power-up they record the gyro while the motors hold still, run an FFT, and move the notch to the strongest peak.

Lab: A radix-2 FFT, and the strongest frequency

  • fft(re, im, n) transforms n complex samples in place, for n a power of two, with the iterative radix-2 algorithm: first reorder the samples by bit-reversed index, then for each stage of size len = 2, 4, ... n, combine pairs len/2 apart with the twiddle factors w = cos(2πk/len) − i·sin(2πk/len). The result is the plain DFT, X[k] = Σ x[t]·e^(−2πi·kt/n), with no scaling.
  • resonance_hz(x, n, fs) finds the strongest frequency in n real samples taken at fs Hz: subtract the samples' mean (the gyro's offset), multiply each by the Hann window 0.5 − 0.5·cos(2πt/n) (without it, leakage from a strong tone hides weaker ones), transform, and return k × fs / n for the bin k with the largest magnitude, searching from the first bin at or above MIN_HZ up to n/2 − 1. Below 20 Hz is the hand swaying and walking, which the gimbal is there to correct, not a resonance. Work on a copy: x must not change.

n is at most FFT_MAX.

Going deeper

Interview question: How would you detect a failing bearing on a factory motor from its vibration?

Answer: Sample the accelerometer fast enough for the bearing's fault frequencies, window the data and run an FFT, then track the energy in the bands where the bearing's defect frequencies (from its geometry and the shaft speed) appear. Compare with a baseline taken when the motor was healthy and alarm on a trend, not one reading.

Interview question: When is the Goertzel algorithm better than an FFT?

Answer: When you need the magnitude at only a few known frequencies, such as DTMF tones or detecting a specific carrier. Goertzel computes one bin with a simple second-order recursion, N multiply-adds and two state variables per frequency, can run sample by sample as data arrives, and does not need N to be a power of two. For more than roughly log2(N) frequencies, a full FFT becomes cheaper.

Interview question: How can you estimate a frequency more precisely than the FFT's bin width?

Answer: Interpolate around the peak bin: fitting a parabola (or a window-specific formula) through the magnitudes of the peak and its two neighbours estimates the true frequency to a fraction of a bin. Zero-padding before the FFT gives a smoother spectrum to interpolate on but adds no real resolution. Alternatively, for a single tone, measure the period directly with zero crossings or a timer's input capture, or use a longer capture.

Explain it: In your own words, explain what spectral leakage is and how a window function reduces it.

Answer: An FFT treats the block of samples as if it repeated endlessly. If the signal does not complete a whole number of cycles in the block, the end does not join smoothly to the start, and that jump looks like a mixture of many frequencies, so energy from a single tone spreads into neighbouring bins instead of appearing in one. A window function multiplies the samples by a curve that starts and ends at zero, removing the jump, so the energy stays concentrated near the true frequency at the cost of a slightly wider peak and a known reduction in amplitude.