Skip to main content

Complementary Filter

Mediumdifficulty

Smoothing handles jitter, but it can't fix a sensor whose readings slowly walk away from the truth. For that you need a second sensor that doesn't drift, and a rule for combining the two.

Two encoders, two different problems​

An arm on a robot usually has two ways to measure its angle:

  • The motor encoder counts ticks at the motor. It's fresh every loop and very fine-grained, but it measures the motor, not the joint. Belt slip, a skipped chain tooth, and gear backlash between them all add up, so the angle you work out from ticks drifts away from the real arm angle over a match. Great over a few seconds, wrong over a few minutes.
  • An absolute encoder on the joint reads the joint angle directly, so slip doesn't add up. It still needs calibrating and can have a fixed offset, it's noisier, and it may update less often than your loop runs. Right on average, rough from moment to moment.

Use only the motor encoder and the arm slowly loses track of where it is. Use only the absolute encoder and the controller reacts to noise. The two sensors fail in opposite ways, which is where the name complementary comes from.

Predict, then correct on the angle circle​

Each loop, take last loop's estimate and add however far the motor encoder says the joint moved. That's a prediction. Then compare it with the absolute encoder and move a small part of the way toward it.

With numbers: last loop's estimate was 1.000 rad. The motor encoder says the joint moved 0.020 rad, so the prediction is 1.020. The absolute encoder reads 1.050, so the prediction is 0.030 rad low. If you correct 5% of that gap, the new estimate is 1.020+0.05×0.030=1.02151.020 + 0.05 \times 0.030 = 1.0215 rad. Fast motion comes from the motor encoder immediately, and the absolute encoder slowly pulls out any drift.

Because these are angles, every difference has to be wrapped so it takes the short way around the circle:

θk−=wrap⁡(θ^k−1+Δθmotor),rk=wrap⁡(θabs−θk−),θ^k=wrap⁡ ⁣(θk−+(1−α)rk).\begin{aligned} \theta^-_k &= \operatorname{wrap}(\hat\theta_{k-1}+\Delta\theta_{\text{motor}}),\\ r_k &= \operatorname{wrap}(\theta_{\text{abs}}-\theta^-_k),\\ \hat\theta_k &= \operatorname{wrap}\!\left(\theta^-_k+(1-\alpha)r_k\right). \end{aligned}

Here θk−\theta^-_k is the prediction, rkr_k is the gap between the absolute reading and the prediction, and 1−α1-\alpha is the fraction of the gap you correct each loop, the 5% in the example. α\alpha is the weight on the prediction, so it sits close to 1. (Careful: that's the opposite of the low-pass filter, where α\alpha was the weight on the new reading.)

The wrapping matters near the seam. A prediction just below +π+\pi and a reading just above −π-\pi are physically almost the same angle, but subtracting them naively gives nearly 2π2\pi, and the filter would swing the long way around.

The demo uses exactly this update. Add slip, then add noise to the absolute encoder, and think about which sensor each problem should make you trust less.

Live demoFusing a motor encoder & an absolute encoder
True arm angleFilter estimate
TrueMotor encoder onlyAbsolute onlyComplementary
High = smooth but drifts · Low = jittery but anchored
Belt slip & backlash: the motor is not the joint.
Motor-encoder-only error: —Fused error: —

Why it's called complementary (optional)​

Away from the wrap seam, the fusion behaves like two filters added together, one on each sensor:

Habs(z)=1−α1−αz−1,Hrel(z)=α(1−z−1)1−αz−1.H_\text{abs}(z)=\frac{1-\alpha}{1-\alpha z^{-1}},\qquad H_\text{rel}(z)=\frac{\alpha(1-z^{-1})}{1-\alpha z^{-1}}.

Here z−1z^{-1} means "one loop ago." The absolute encoder goes through a low-pass filter, so its slow, accurate average gets through and its fast noise doesn't. The motor encoder goes through the matching high-pass filter, so its fast motion gets through and its slow drift doesn't. Add the two formulas and you get exactly 1, which is what "complementary" means.

Math explorerThe frequency split: each sensor keeps its own band
frequency (Hz, log; Nyquist 50.0 Hz)exact sampled magnitudeabsolute owns the slow truthmotor encoder owns the fast motioncomplex responses sum to 1; magnitudes include phasecrossover 0.32 Hz
time constant τ = −Δt/ln(α): 0.49 sexact discrete crossover: 0.32 HzNyquist limit: 50.0 Hzbelow f_c: absolute anchors · above f_c: motor encoder steers
absolute-encoder path — low-passmotor-encoder path — high-passcrossover frequency

In the graph, the rose curve is the absolute encoder's low-pass and the teal curve is the motor encoder's high-pass. (Strictly, it's the complex values that add to 1. The magnitudes plotted here don't quite, because each path also shifts the timing a little.) The graph stops at the Nyquist frequency for the loop rate, 1/(2Δt)1/(2\Delta t).

Tip
Watch both lines

In the live demo, the motor-encoder line slides away from the truth and the absolute line is fuzzy, but the combined estimate stays smooth and on target. It costs a few arithmetic operations and three angle wraps per loop.

One line per loop​

The motor encoder comes in as a change since last loop, and the absolute encoder as a reading. Start the estimate from the absolute encoder so it begins in the right place:

FTCFuse a motor encoder with an absolute encoder
private static final double TAU = 0.5; // fusion time constant, seconds
private static final double RAD_PER_TICK = 2 * Math.PI / TICKS_PER_REV;

private double angle; // seed from the absolute encoder, not from zero
private double lastTicks;
private boolean seeded;

double update(double ticks, double absRad, double dt) {
// NOTE: here alpha weights the PREDICTION, so it is 1 - the low-pass alpha.
double alpha = Math.exp(-dt / TAU); // loop-rate independent

if (!seeded) { // never difference against a zero we never read
angle = wrap(absRad);
lastTicks = ticks;
seeded = true;
return angle;
}

double delta = (ticks - lastTicks) * RAD_PER_TICK;
lastTicks = ticks;

double prediction = wrap(angle + delta);
double innovation = wrap(absRad - prediction);
angle = wrap(prediction + (1 - alpha) * innovation);
return angle;
}
ExerciseBoth extremes of alpha

With α=1\alpha = 1 the correction disappears. Which sensor are you using? With α=0\alpha = 0 the prediction is thrown away. Which one now?

Show solution

α=1\alpha = 1 leaves angle = prediction, so it's the motor encoder alone: smooth, and drifting forever. α=0\alpha = 0 leaves angle = absRad, so it's the absolute encoder alone: accurate on average and jittery every loop. τ\tau sets where you sit in between, in seconds rather than loops.

ExerciseWhy every line wraps

The absolute encoder rolls over from +π+\pi to −π-\pi. Remove the wrap calls and trace a loop across that point. Where does it go wrong?

Show solution

In innovation. Just past the seam, absRad has rolled over to just above −π-\pi while prediction is still just below +π+\pi. Their difference comes out around −2π-2\pi instead of nearly zero, so the filter thinks it's a full turn off and drags angle backwards on the first loop after the rollover.

The last three lines say: trust the motor encoder's motion, see how far that has drifted from the absolute encoder, and move a little of the way back.

The textbook version

Most textbooks teach this filter with a gyro and an accelerometer: the gyro is fast but drifts, and the accelerometer's gravity reading is shaky but doesn't drift. The math is the same. On an FTC robot the IMU already does that fusion internally. Any fast sensor that drifts plus any slow sensor that doesn't will work, like a gyro heading corrected by an occasional vision bearing.

Here you pick the blend by hand, and it stays fixed. The Kalman filter, next, works out the blend every loop from how uncertain each source currently is.

Sources & references
  • WPILib: Filters - robotics filtering reference for combining sensor signals.
  • Tyler Veness, Controls Engineering in FRC - estimator and controls context for blending model and sensor information.
  • Kalman Filter - the next Control Lab lesson, where the fixed blend becomes an uncertainty-weighted gain.