Signal Filtering
Filtering in Line Tracking
Filtering helps clean up noisy sensor signals, especially from optosensors that can flicker due to lighting, dirt, or contrast issues.
πΈ Low-pass Filter (LPF)
-
Use: Smooth out high-frequency noise from sensor readings.
-
Example (Simple IIR filter):
python
CopyEdit
filtered_value = alpha * new_reading + (1 - alpha) * previous_valuealpha~ 0.1 to 0.5 depending on how responsive you want it.
-
Effect: Makes your error signal smoother and avoids jittery corrections.
πΈ Median Filter
-
Use: Rejects spikes caused by momentary bad readings.
-
How it works: Keeps a short history of sensor values and outputs the median.
-
Good when: You get occasional garbage values from one sensor.
π§ 2. Adaptive Filtering
Adaptive filters adjust themselves based on signal conditions. They're useful when sensor noise or system behavior changes over time.
Example: LMS (Least Mean Squares) Adaptive Filter
-
Tries to predict the signal and reduce the error between the predicted and actual signal.
-
Use case: Tracking slowly drifting sensor baselines, e.g., optosensors that vary as lighting changes.
Realistic Use:
Most student-level line followers donβt need this, unless:
-
You have unpredictable lighting, or
-
Youβre doing sensor fusion (e.g., line sensor + IMU),
-
Youβre building a high-speed competition robot where precision matters.
π 3. What About Non-LTI Systems?
LTI = Linear Time-Invariant. Most classical control (like PID) assumes the system is LTI.
But your robot is not LTI:
-
Non-linear: Motor response isnβt linear. Friction, battery level, PWM β speed linearly.
-
Time-varying: Battery voltage drops over time, sensors degrade, terrain changes.
Why it matters:
-
PID tuning might not work well everywhere.
-
You get instability if you don't account for these effects.
Solutions:
π§ 1. Gain Scheduling
- Switch PID parameters based on known modes (e.g., high speed vs low speed).
π§ 2. Adaptive Control
-
System learns or adapts parameters on the fly (e.g., adjusts Kp, Ki, Kd based on error trends).
-
Can use model-based approaches (like MIT rule, Lyapunov methods), or even machine learning in advanced cases.
π‘ 3. Non-linear Control
- Like sliding mode control or feedback linearization, but probably overkill unless you're building advanced robotics.
π― TL;DR for your use case
| Concept | When to Use | Benefit |
|---|---|---|
| Low-pass filter | Always | Smooths sensor noise |
| Median filter | Noisy signals | Removes spikes |
| Adaptive filter | Varying noise | Adjusts to changing conditions |
| Gain scheduling | Multi-mode robot | Optimized control |
| Adaptive control | Changing dynamics | Self-tuning |
| Non-linear control | High precision robots | Advanced compensation |
.
π§ What Is a Kalman Filter (KF)?
A Kalman Filter is a recursive estimator β it fuses noisy sensor measurements with a model of the system to produce a best estimate of the systemβs current state.
It assumes:
-
The system is linear (or extended to non-linear in EKF),
-
Thereβs process noise (your system model isnβt perfect),
-
And measurement noise (your sensors arenβt perfect).
π When Should You Use a Kalman Filter?
| Use Case | Kalman Filter? | Why |
|---|---|---|
| Just smoothing a noisy line sensor | β | Overkill β use low-pass or median filter. |
| Fusing multiple noisy sensors (e.g., IMU + encoders) | β | KF shines at sensor fusion. |
| Estimating position, velocity, heading from multiple inputs | β | Helps track state with higher confidence. |
| Your system is very dynamic or changes fast | β | KF adapts to measurement vs model trust. |
| Only a single sensor with low noise | β | Simpler filters (moving average, IIR) work fine. |
π¦Ύ Line-Following Robot β Do You Need Kalman?
Probably not for basic line tracking, unless you're doing one of these:
β Use Kalman if:
-
You combine line sensors with IMU (for estimating heading/position),
-
Youβre implementing dead reckoning (using wheel encoders to estimate position),
-
You have very noisy sensors and want smooth, predictive control,
-
You want to predict future line position at high speed (advanced!).
π§ Example Use Case (Advanced Line-Follower):
You have:
-
4 optosensors for line position,
-
An IMU giving yaw rate,
-
Wheel encoders giving velocity.
You want to estimate:
-
Actual position on track (even if line is lost),
-
Heading angle drift (to correct motor speeds),
-
Predict future trajectory.
β‘οΈ Kalman filter can fuse the sensor data to estimate the robot's true position even when sensors glitch or the line temporarily disappears.
β¨ Extended Kalman Filter (EKF)
If your robot model is non-linear (e.g., turning on curves), use an EKF:
-
Linearizes the model at each step
-
More complex but widely used in mobile robotics and SLAM
π¦ TL;DR
Use a Kalman Filter when:
-
You're fusing multiple sensor sources,
-
You want to track hidden or noisy system states (like position, angle, velocity),
-
You're working in non-ideal, fast-changing environments,
-
You need prediction + correction in control (not just filtering).
Professional Context: Industrial & Automotive Signal Processing
Your simple low-pass filter works for smoothing sensor noise. Professional systems use sophisticated signal processing chains for reliability, safety, and performance. Here's how they compare:
Signal Processing Comparison
| Feature | Your Robot | Industrial | Automotive | Aerospace/Defense |
|---|---|---|---|---|
| Filtering | Software IIR | Hardware + software | Multi-stage, redundant | Certified algorithms |
| Sample rate | 50-100 Hz | 1-100 kHz | 1-10 kHz | 100+ Hz, deterministic |
| Anti-aliasing | None | Required by design | Mandatory | Proven, tested |
| Sensor fusion | Optional | Common | Essential (ADAS) | INS/GPS, multi-sensor |
| Redundancy | None | Optional | ASIL-dependent | Triple-redundant |
| Certification | None | Optional | ISO 26262 | DO-178C, MIL-STD |
Signal Conditioning Chain
Professional systems don't just filter in softwareβthey condition signals at every stage:
Your robot:
Sensor βββΊ ADC βββΊ Software filter βββΊ Control
(raw) (maybe)
Industrial signal chain:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β Sensor βββΊ Amplifier βββΊ Anti-alias βββΊ ADC βββΊ Digital βββΊ β
β (signal filter (high filter Use β
β conditioning) (hardware) res) (FIR/IIR) β
β β
β Each stage has a purpose: β
β β’ Amplifier: Scale signal to ADC range, impedance matching β
β β’ Anti-alias: REMOVE frequencies above Nyquist BEFORE ADC β
β β’ High-res ADC: 16-24 bit, differential, low noise β
β β’ Digital filter: Programmable, precise characteristics β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Why anti-aliasing matters:
Your ADC samples at 100 Hz
Noise at 150 Hz exists in signal
Without anti-alias filter: 150 Hz appears as 50 Hz (aliased!)
β You filter a "ghost" signal that isn't real
β Control system responds to phantom noise
Kalman Filter Variants
Beyond basic Kalman, professionals use specialized variants:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Kalman Filter Family β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Linear Kalman Filter (KF) β
β βββ Your robot could use this β
β βββ Assumes linear system: x[k+1] = A*x[k] + B*u[k] + w β
β βββ Optimal for linear systems with Gaussian noise β
β βββ Computationally cheap β
β β
β Extended Kalman Filter (EKF) β
β βββ Most common in practice β
β βββ Linearizes nonlinear systems at each step β
β βββ Used in: GPS receivers, robot localization, automotive β
β βββ Can diverge if system is highly nonlinear β
β β
β Unscented Kalman Filter (UKF) β
β βββ Better for highly nonlinear systems β
β βββ Uses "sigma points" instead of linearization β
β βββ More accurate than EKF, slightly more expensive β
β βββ Used in: spacecraft attitude, advanced ADAS β
β β
β Particle Filter (Sequential Monte Carlo) β
β βββ Non-parametric: doesn't assume Gaussian β
β βββ Can handle multi-modal distributions β
β βββ Computationally expensive (many particles needed) β
β βββ Used in: SLAM, tracking, computer vision β
β β
β Information Filter β
β βββ Inverse of Kalman (works with precision, not covariance) β
β βββ Better for multi-sensor fusion β
β βββ Used in: distributed sensor networks β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Automotive Sensor Fusion
Modern vehicles fuse many sensors for safety features:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ADAS Sensor Fusion Architecture β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Raw Sensors: β
β βββββββββββ βββββββββββ βββββββββββ βββββββββββ βββββββββββ β
β β Camera β β Radar β β Lidar β β USS β β IMU β β
β β (vision)β β (range) β β (3D) β β(parking)β β (motion)β β
β ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ β
β β β β β β β
β βββββββββββββ΄ββββββββββββ΄ββββββββββββ΄ββββββββββββ β
β β β
β ββββββββββββΌβββββββββββ β
β β Sensor Fusion β β
β β (EKF / UKF) β β
β β β β
β β β’ Object tracking β β
β β β’ Position/velocityβ β
β β β’ Classification β β
β ββββββββββββ¬βββββββββββ β
β β β
β βββββββββββββββββββββΌββββββββββββββββββββ β
β β β β β
β βΌ βΌ βΌ β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β AEB β β ACC β β LKA β β
β β(Braking) β β (Cruise) β β(Lane Keepβ β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β
β Why fuse? β
β β’ Camera: Good classification, poor range β
β β’ Radar: Good range/velocity, poor resolution β
β β’ Lidar: Good 3D, expensive, weather-sensitive β
β β’ Fusion: Combines strengths, covers weaknesses β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Aerospace INS/GPS Fusion
The gold standard for navigation uses tightly-coupled sensor fusion:
Your robot (dead reckoning):
Encoders β Integrate β Position estimate
Problem: Drift accumulates forever
INS/GPS Fusion (aircraft, missiles, spacecraft):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β IMU (Inertial Measurement Unit) β
β βββ 3-axis accelerometer β
β βββ 3-axis gyroscope β
β βββ Very high rate (100-1000 Hz) β
β βββ Short-term accurate β
β βββ Drifts over time (gyro bias, accelerometer bias) β
β β
β GPS (Global Positioning System) β
β βββ Absolute position (no drift!) β
β βββ Low rate (1-10 Hz) β
β βββ Can be jammed, multipath errors β
β βββ No velocity/attitude directly β
β β
β Kalman Filter Fusion: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β β State: [position, velocity, attitude, IMU biases] β β
β β β β
β β Predict: Use IMU to propagate state (fast, drifts) β β
β β Update: Use GPS to correct drift (slow, accurate) β β
β β β β
β β Result: Best of both worlds β β
β β β’ High-rate, smooth position (from IMU) β β
β β β’ Long-term accuracy (from GPS) β β
β β β’ Continues working if GPS lost briefly β β
β β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Tight coupling: GPS pseudoranges used directly in KF
Loose coupling: GPS position used to correct INS
ESC Sensor Fusion Example
Electronic Stability Control fuses multiple sensors in real-time:
Your line follower:
4 optocouplers β Calculate position β PID β Motors
(No fusion, just direct measurement)
ESC (Electronic Stability Control):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β Sensors (all sampled at 100+ Hz): β
β βββ Yaw rate gyroscope (rotation) β
β βββ Lateral acceleration (sideways G-force) β
β βββ Steering wheel angle β
β βββ Wheel speed Γ 4 (ABS sensors) β
β βββ Brake pressure β
β β
β State Estimation (Kalman Filter): β
β βββ Vehicle yaw rate (how fast spinning) β
β βββ Side-slip angle (are we sliding?) β
β βββ Tire slip ratios Γ 4 β
β βββ Road friction estimate (!!) β
β β
β Control Decision: β
β βββ Compare desired yaw (from steering) vs actual yaw β
β βββ If difference too large β intervene β
β βββ Brake individual wheels to correct β
β β
β Note: Side-slip angle can't be measured directly! β
β Must be ESTIMATED from other sensors via KF β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Digital Filter Design
Professional systems carefully design filters for specific requirements:
Your robot:
alpha = 0.2 # "seems to work"
filtered = alpha * new + (1-alpha) * old
Professional filter design:
Requirements:
βββ Passband: 0-20 Hz (signal of interest)
βββ Stopband: >50 Hz (noise to remove)
βββ Ripple: <0.1 dB (flatness in passband)
βββ Attenuation: >60 dB (noise rejection)
βββ Phase: Linear (no distortion)
Design process:
1. Specify requirements mathematically
2. Choose filter type (Butterworth, Chebyshev, Elliptic, FIR)
3. Calculate coefficients (MATLAB, Python scipy)
4. Verify frequency response
5. Implement and test
Filter types:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FIR (Finite Impulse Response) β
β βββ Always stable β
β βββ Linear phase possible (no distortion) β
β βββ More coefficients needed β
β βββ Used when phase matters (audio, communications) β
β β
β IIR (Infinite Impulse Response) β
β βββ Can be unstable if poorly designed β
β βββ Fewer coefficients for same performance β
β βββ Nonlinear phase β
β βββ Used when efficiency matters (control systems) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Professional filter design with scipy (free!)
from scipy import signal
import numpy as np
# Design a 4th-order Butterworth low-pass filter
# Cutoff: 20 Hz, Sample rate: 200 Hz
fs = 200 # Sample rate
fc = 20 # Cutoff frequency
order = 4
# Normalized cutoff (0 to 1, where 1 = Nyquist)
Wn = fc / (fs / 2)
# Design filter
b, a = signal.butter(order, Wn, btype='low')
# Check frequency response
w, h = signal.freqz(b, a, fs=fs)
# For embedded: convert to second-order sections (more stable)
sos = signal.butter(order, Wn, btype='low', output='sos')
# Apply filter to data
filtered_data = signal.sosfilt(sos, raw_data)
Redundancy and Voting
Safety-critical systems don't trust single sensors:
Your robot:
One sensor β One reading β Trust it
Flight control (triple redundancy):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β Sensor A βββββ β
β β β
β Sensor B βββββΌββββΊ Voting Logic ββββΊ Use this value β
β β (median, or β
β Sensor C βββββ fault detection) β
β β
β Scenarios: β
β A=100, B=100, C=100 β Output 100 (all agree) β
β A=100, B=100, C=999 β Output 100 (C is faulty, ignore) β
β A=100, B=200, C=150 β Output 150 (median) β
β β
β Plus: Each sensor has its own signal conditioning chain β
β Different sensor types when possible (diverse) β
β Continuous monitoring for sensor health β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
What the Industry Uses
| Tool/Library | Use | Cost |
|---|---|---|
| MATLAB Signal Processing Toolbox | Filter design, analysis | $$$$ |
| scipy.signal | Filter design, analysis | Free |
| FilterPy | Kalman filters in Python | Free |
| Robot Operating System (ROS) | Sensor fusion packages | Free |
| dSPACE | HIL testing of filters | $$$$ |
| NI LabVIEW | Signal processing | $$$ |
| Analog Devices (hardware) | Signal conditioning ICs | $ per chip |
| Texas Instruments (hardware) | ADCs, signal chain | $ per chip |
Hardware Limits Principle
What Software Can and Cannot Fix
Software CAN improve: - Noise reduction β digital filtering - Sensor fusion β Kalman filter, complementary filter - Drift compensation β bias estimation - Outlier rejection β median filter, fault detection - Adaptability β adaptive filters, tunable parameters
Software CANNOT fix: - Aliasing β needs hardware anti-alias filter BEFORE ADC - ADC resolution β 10-bit noise can't become 16-bit clean - Sensor bandwidth β physical sensor can't respond faster - Quantization noise β inherent to digital conversion - Sensor physics β magnetometer near motor will always be noisy - Correlation β if two sensors see same noise source, fusion won't help
The lesson: A Kalman filter can optimally fuse noisy sensors, but it can't create information that isn't there. If your gyroscope drifts 1Β°/s and you have no absolute reference, Kalman can slow the drift but not eliminate it. Hardware choices (sensor quality, anti-aliasing, shielding) determine the floor; software determines how close you get to that floor.
Real Example: IMU Filtering
| Challenge | Your Robot | Professional Solution |
|---|---|---|
| Gyro drift | Ignore it | Fuse with magnetometer/GPS |
| Accelerometer noise | Low-pass filter | Kalman with motion model |
| Vibration from motors | Hope it averages | Hardware isolation + notch filter |
| Temperature effects | Ignore | Calibration tables + compensation |
| Magnetic interference | Ignore | Hard/soft iron calibration |
Your robot's IMU pipeline:
Professional IMU pipeline:
Raw IMU data
β
βββ Hardware: Anti-alias filter on ADC inputs
β
βββ Calibration: Apply factory + runtime calibration
β βββ Gyro bias (measured at rest)
β βββ Accelerometer offset and scale
β βββ Temperature compensation tables
β
βββ Filtering: Remove vibration (notch at motor frequency)
β
βββ Sensor Fusion (EKF/UKF):
β βββ Predict: Use gyro to propagate attitude
β βββ Update: Correct with accelerometer (gravity direction)
β βββ Update: Correct with magnetometer (heading)
β
βββ Output: Calibrated, filtered, fused attitude estimate
Further Reading
- Kalman Filter Tutorial - Visual explanation
- FilterPy Documentation - Python Kalman filters
- Sensor Fusion on Mobile Devices - Google I/O talk
- Introduction to Random Signals and Applied Kalman Filtering - Brown & Hwang textbook