FFT1D – Fixed-Point Fast Fourier Transform

Real-world use: an industrial bearing monitor watches for a specific fault frequency. A 64-point fixed-point FFT turns the raw vibration stream into spectral bins, so a tiny classifier reads the energy at the fault harmonic directly instead of spending model capacity learning the Fourier basis from raw samples.

tinymind provides FFT1D, a standalone radix-2 decimation-in-time FFT for power-of-two lengths. It is designed for embedded signal processing where frequency-domain features feed into a neural network classifier. All dimensions are compile-time template parameters with zero dynamic allocation.

Why FFT for Embedded ML?

Many embedded ML tasks involve classifying signals that are better separated in the frequency domain than in the time domain:

  • Vibration analysis – bearing fault frequencies, motor harmonics
  • Audio keyword spotting – spectral features before a small classifier
  • IMU/accelerometer – gait analysis, gesture recognition via frequency signatures
  • ECG/PPG – heart rate extraction, arrhythmia frequency patterns

A time-domain signal fed directly into a neural network requires the network to learn the Fourier basis – wasting capacity. Computing the FFT first gives the network frequency bins as input, dramatically reducing the model size needed for the same accuracy.

Template Declaration

template<typename ValueType, size_t N>
class FFT1D

Template Parameters:

  • ValueType – Numeric type (QValue, float, or double)
  • N – FFT length (must be a power of two, >= 2)

Static Properties:

  • Length = N
  • HalfLength = N / 2
  • NumStages = log2(N)

Compile-Time Constraints:

static_assert((N & (N - 1)) == 0, "FFT length must be a power of two.");
static_assert(N >= 2, "FFT length must be at least 2.");

Design for Fixed-Point

Three design choices make FFT1D practical on MCUs without an FPU:

1. Scaled Butterfly

Each butterfly stage divides results by 2, giving a total scaling of 1/N across the forward transform. This prevents intermediate overflow in fixed-point arithmetic – a Q8.8 value can never exceed the representable range during computation, regardless of input magnitude.

The inverse FFT uses unscaled butterflies internally, so inverse(forward(x)) == x with no additional division step.

2. Compile-Time Bit-Reversal Table

The radix-2 FFT requires a bit-reversal permutation before the butterfly stages. On ARM Cortex-M0, which lacks a barrel shifter (each shift is a single-bit operation), computing bit-reversal at runtime is expensive.

Since N is a template parameter, FFT1D generates the entire permutation table at compile time using constexpr:

namespace detail {
    template<size_t N, size_t NumStages>
    struct BitReversalTable
    {
        // uint8_t up to N = 256, uint16_t up to N = 65536, size_t beyond.
        typedef typename BitReversalIndex<N>::type IndexType;

        IndexType indices[N];
        constexpr BitReversalTable() : indices{}
        {
            for (size_t i = 0; i < N; ++i)
            {
                size_t x = i;
                size_t result = 0;
                for (size_t b = 0; b < NumStages; ++b)
                {
                    result = (result << 1) | (x & 1);
                    x >>= 1;
                }
                indices[i] = static_cast<IndexType>(result);
            }
        }
    };
}

The table is stored in flash as a constant array. At runtime, the permutation is a linear scan with swaps – no shifts at all. Each entry is the narrowest unsigned type that holds the indices 0..N-1, so the table is one byte per point up to N = 256 and two bytes up to N = 65,536. QFFT1D uses the same table.

FFT Size Table Size (bytes) Shifts Eliminated
64 64 ~384
128 128 ~896
256 256 ~2,048

3. Externally-Provided Twiddle Factors

The FFT twiddle factors are cos(-2*pi*k/N) and sin(-2*pi*k/N). For float/double, these can be computed with std::cos/std::sin. For Q-format, there are no built-in trig functions, so the values must be pre-computed externally and loaded via setTwiddleFactors().

tinymind includes sin/cos lookup tables generated by the activation table generator (see Activation Lookup Tables), or you can compute exact twiddle values offline and embed them in your application.

Example: Floating-Point

#include "fft1d.hpp"
#include <cmath>

const size_t N = 256;
tinymind::FFT1D<double, N> fft;

// Compute twiddle factors
double cosTable[N / 2], sinTable[N / 2];
for (size_t k = 0; k < N / 2; ++k)
{
    cosTable[k] = std::cos(-2.0 * M_PI * k / N);
    sinTable[k] = std::sin(-2.0 * M_PI * k / N);
}
fft.setTwiddleFactors(cosTable, sinTable);

// Transform a signal
double real[N] = { /* sensor samples */ };
double imag[N] = {}; // zero for real-valued input

fft.forward(real, imag);

// Compute power spectrum (no sqrt needed)
double magSq[N];
tinymind::FFT1D<double, N>::magnitudeSquared(real, imag, magSq);

// Feed first N/2 bins into a classifier
classifier.feedForward(magSq);

Example: Fixed-Point (Q8.8)

#include "fft1d.hpp"

typedef tinymind::QValue<8, 8, true, tinymind::RoundUpPolicy> Q8_8;
const size_t N = 64;
tinymind::FFT1D<Q8_8, N> fft;

// Pre-computed twiddle factors for N=64
// cos(-2*pi*k/64) and sin(-2*pi*k/64) for k=0..31
// These can be generated offline and stored in flash
Q8_8 cosTable[N / 2];
Q8_8 sinTable[N / 2];

// Example: k=0 -> cos(0)=1, sin(0)=0
cosTable[0] = Q8_8(1, 0);
sinTable[0] = Q8_8(0, 0);
// k=1 -> cos(-pi/32)=0.995, sin(-pi/32)=-0.098
cosTable[1] = Q8_8(0, 254); // ~0.995
sinTable[1] = Q8_8(-1, 231); // ~-0.098
// ... remaining values pre-computed similarly ...

fft.setTwiddleFactors(cosTable, sinTable);

Q8_8 real[N]; // fill with sensor data
Q8_8 imag[N]; // zero-initialized for real input
for (size_t i = 0; i < N; ++i)
    imag[i] = Q8_8(0);

fft.forward(real, imag);

// Magnitude squared avoids sqrt (unavailable in fixed-point)
Q8_8 magSq[N];
tinymind::FFT1D<Q8_8, N>::magnitudeSquared(real, imag, magSq);

Pipeline: FFT + Neural Network

A typical embedded ML pipeline: sample sensor data, compute FFT, classify frequency bins:

#include "fft1d.hpp"
#include "neuralnet.hpp"

// 128-point FFT -> 64 magnitude bins -> small classifier
typedef tinymind::FFT1D<double, 128> FFTType;
// Neural network: 64 inputs (N/2 useful bins) -> 16 hidden -> 4 outputs
// (Configure via properties struct as usual)

FFTType fft;
// ... set twiddle factors ...

double sensorData[128];
double real[128], imag[128];
double magSq[128];
double features[64]; // first N/2 bins (Nyquist symmetry)

// Sample -> FFT -> classify
for (size_t i = 0; i < 128; ++i)
{
    real[i] = sensorData[i];
    imag[i] = 0.0;
}

fft.forward(real, imag);
FFTType::magnitudeSquared(real, imag, magSq);

// Only first N/2 bins are unique (real input symmetry)
for (size_t i = 0; i < 64; ++i)
    features[i] = magSq[i];

classifier.feedForward(features);

Inverse FFT

The inverse transform recovers time-domain data from frequency-domain representation:

fft.forward(real, imag);
// ... modify spectrum (filtering, denoising) ...
fft.inverse(real, imag);
// real[] now contains the filtered time-domain signal

The inverse uses the conjugate trick internally: IFFT(X) = conj(DFT(conj(X))). It uses unscaled butterflies so that inverse(forward(x)) == x – no manual scaling needed.

Memory Footprint

All storage is statically allocated. The FFT object stores only the twiddle factor tables:

Component Count Purpose
Twiddle cosines N/2 cos(-2pik/N)
Twiddle sines N/2 sin(-2pik/N)
Bit-reversal table N Compile-time, stored in flash; 1 byte per entry up to N = 256

Working memory (caller-provided arrays):

Array Count Purpose
real[] N Real parts (input/output)
imag[] N Imaginary parts (input/output)
magSq[] N Magnitude squared (optional)

Example Footprints

FFT Size ValueType Object RAM Working RAM Flash (bit-rev table) Total
64 Q8.8 128 B 384 B 64 B 576 B
128 Q8.8 256 B 768 B 128 B 1,152 B
256 Q8.8 512 B 1,536 B 256 B 2,304 B
64 Q16.16 256 B 768 B 64 B 1,088 B
128 Q16.16 512 B 1,536 B 128 B 2,176 B

A 64-point Q8.8 FFT + a small 32-input classifier fits comfortably in 2 KB of RAM – feasible on any Cortex-M0 device.

Q-Format Precision Considerations

Twiddle Factor Precision

Twiddle factors are sine/cosine values in [-1, 1]. Q8.8 gives 8 fractional bits (~0.004 resolution), which introduces ~0.2% error per butterfly. After log2(N) stages:

FFT Size Stages Approximate Precision Loss
64 6 ~1-2 fractional bits
128 7 ~2-3 fractional bits
256 8 ~3 fractional bits

Recommendation: For FFT sizes above 128, use Q16.16 for better precision. Q8.8 is best for N <= 128.

Scaled Butterfly Overflow Safety

The divide-by-2 scaling at each stage means intermediate values never exceed the input range. A Q8.8 value with fixed part in [-128, 127] stays within bounds regardless of FFT size. This eliminates the need for saturation checks in the butterfly – the WrapPolicy is sufficient.

Measured Performance

FFT1D<Q8.8, N> (the type of the fixed-point example above), cycles per forward transform, arm-none-eabi-gcc 13.2.1, -O3, median of 33 runs, output bit-identical to the host’s:

FFT Size Cortex-M0+ (L031) Time @ 32 MHz Cortex-M4F (F411) Time @ 100 MHz
64 39,340 1.2 ms 15,047 0.15 ms
128 89,790 2.8 ms 33,787 0.34 ms
256 202,696 6.3 ms 74,548 0.75 ms

-O2 is within 2% of these on both cores. Real-time processing at a 1 kHz sample rate is feasible up to 256-point FFTs on a 32 MHz Cortex-M0+: a 256-sample window takes 256 ms to fill and about 6 ms to transform. For int16 data, QFFT1D and QRFFT1D are faster at every size. The bench is benchmarks/fft_onboard (IMG=fft1d).

Use Cases

  • Vibration monitoring – compute FFT of accelerometer data, classify bearing fault frequencies with a small Q8.8 network
  • Audio feature extraction – FFT -> magnitude bins -> keyword spotting classifier, replacing MFCC pipelines that need log/DCT
  • Motor current analysis – detect harmonic patterns indicating motor degradation
  • Structural health monitoring – frequency-domain features from strain gauges or piezoelectric sensors

Int8 Quantized Counterpart

tinymind ships QFFT1D<N>, a radix-2 DIT FFT on int16 buffers with Q1.15 twiddle factors. Twiddles are caller-owned, built host-side by buildQFFTTwiddles(n, cos_out, sin_out). Scaled butterflies (right-shift by 1 per stage; total scaling 1/N) keep the int16 working register bounded. magnitudeSquared emits int32; the int8 boundary on either side is expressed as an ordinary Requantizer. Inverse via the conjugate trick. See Int8 Affine Quantization for the surrounding integer pipeline.

Real-input FFT: QRFFT1D

Audio, vibration and IMU front ends feed the FFT real samples. A complex FFT of a real signal, with the imaginary buffer zeroed, spends half its input on zeros and half its output on bins that mirror the other half. QRFFT1D<N> takes the N real samples and returns only the N/2 + 1 distinct bins, with the same 1/N scaling as QFFT1D<N>::forward:

int16_t cos_t[N / 2], sin_t[N / 2];
tinymind::buildQFFTTwiddles(N, cos_t, sin_t);   // the same table QFFT1D<N> uses

tinymind::QRFFT1D<N> rfft;
rfft.twiddle_cos = cos_t;
rfft.twiddle_sin = sin_t;

int16_t samples[N];                              // real input, left unchanged
int16_t re[tinymind::QRFFT1D<N>::NumBins];       // N/2 + 1 bins
int16_t im[tinymind::QRFFT1D<N>::NumBins];
int32_t power[tinymind::QRFFT1D<N>::NumBins];
rfft.forward(samples, re, im);                   // im[0] and im[N/2] are 0
tinymind::QRFFT1D<N>::magnitudeSquared(re, im, power);

It packs the samples into N/2 complex values (even samples real, odd samples imaginary), runs an N/2-point complex FFT on them, and separates the even and odd spectra in a final split step. At N = 256 that is 448 butterflies, 64 of them multiply-free, plus 128 split outputs, against 1,024 butterflies for QFFT1D<256>. Measured on two Cortex-M boards, it runs a little over twice as fast as QFFT1D with a zeroed imaginary buffer (see the table below). It reads the samples from a const buffer it leaves unchanged and writes N + 2 int16 values of output: when the samples already sit in their own buffer (an ADC or DMA buffer), that is the whole work space, against the 2N values QFFT1D needs for its in-place real and imaginary buffers. Counting the input buffer, QRFFT1D uses two int16 values more.

Cycles per forward transform at -O3, arm-none-eabi-gcc 13.2.1, twiddle tables in flash, median of 33 runs; both transforms reproduce the host’s output bit for bit:

N Cortex-M4F (F411) QFFT1D QRFFT1D Speedup Cortex-M0+ (L031) QFFT1D QRFFT1D Speedup
64 10,136 4,685 2.16× 24,575 11,657 2.11×
128 22,757 10,808 2.11× 55,290 27,013 2.05×
256 50,165 24,103 2.08× 124,247 60,255 2.06×
512 112,346 53,427 2.10× 269,153 133,729 2.01×
1024 233,516 118,027 1.98×      

At N = 256 that is 0.24 ms against 0.50 ms on the 100 MHz Cortex-M4F, and 1.9 ms against 3.9 ms on the 32 MHz Cortex-M0+ (whose 8 KB of RAM stops the bench at N = 512). The QFFT1D column leaves out copying the samples in and zeroing the imaginary buffer, which a real-input caller also pays (1 to 3% at -O3). The -O2 figures, the tables placed in RAM, and the bench itself are in benchmarks/fft_onboard; across all of them the speedup stays between 1.98 and 2.23.

On a core with a saturating instruction (__ARM_FEATURE_SAT, such as the Cortex-M4) each butterfly saturates its four outputs with SSAT; elsewhere with a plain conditional. On the Cortex-M4F at -O3 a radix-2 butterfly costs 46 to 53 cycles, and 117 to 128 on the Cortex-M0+.

Packing two real samples into one complex value lets a component of the inner FFT reach √2 times full scale, which a plain packed FFT would saturate on full-scale input such as clipped audio. QRFFT1D takes that headroom in the first inner stage, whose twiddle is exactly 1, so no int16 input can saturate an intermediate. The price is a little precision: against an exact DFT / N its largest bin error is about 1.3 to 1.7 times QFFT1D’s on the same input, which is a few LSB of the 16-bit spectrum, and its bins differ from QFFT1D’s by at most log2(N) LSB. Use QFFT1D<N> with a zeroed imaginary buffer when those LSB matter more than the halved work. The input buffer must not overlap the outputs.


Back to top

Dan McLeran — danmcleran@gmail.com — MIT License

This site uses Just the Docs, a documentation theme for Jekyll.