How to filter sensor noise in software or hardware?

 Filtering sensor noise is essential for ensuring stable and accurate readings in embedded and control systems. You can use hardware filtering, software filtering, or a combination of both, depending on the type of sensor, system constraints, and noise characteristics.




1. Hardware Filtering Techniques

 a) Low-Pass RC Filter

  • Purpose: Attenuates high-frequency noise before ADC sampling.

  • How: Place a resistor (R) in series and a capacitor (C) to ground.

  • Cutoff Frequency:

    fc=12πRC​
  • Example: For slow-changing analog signals like temperature or voltage.

 b) Shielding & Grounding

  • Use twisted pair cables and shielded enclosures to reduce EMI.

  • Proper star grounding to avoid ground loops.

c) Ferrite Beads and Chokes

  • Block high-frequency noise on power or signal lines.

 d) Analog Filters (Active Filters)

  • Use op-amp based low-pass, band-pass, or notch filters to remove unwanted frequencies precisely.


2. Software Filtering Techniques

 a) Moving Average Filter

  • Simple and effective for reducing random noise.

  • Stores a window of past N readings and returns the average.

c

float moving_average(float *buffer, int size) { float sum = 0; for(int i = 0; i < size; i++) sum += buffer[i]; return sum / size; }

 b) Exponential Moving Average (EMA) / Low-pass IIR Filter

  • Less memory, more responsive to recent data.

  • Formula:

    yn=αxn+(1α)yn1​
  • α (alpha) controls smoothing (0 < α < 1)

c

float ema_filter(float x, float prev_y, float alpha) { return alpha * x + (1 - alpha) * prev_y; }

 c) Median Filter

  • Excellent for eliminating impulse noise (spikes).

  • Sorts a sliding window and picks the middle value.

c

// For small buffers (e.g., size = 3 or 5)

 d) Kalman Filter (Advanced)

  • Combines noisy sensor readings with a predictive model.

  • Common in robotics, IMUs, GPS, etc.

  • Requires modeling of process and measurement noise.

 e) Complementary Filter


When to Use Which Filter

Sensor TypeBest Filtering Approach
Temperature / LightMoving Average, EMA
Accelerometer / GyroComplementary, Kalman
Analog voltage inputRC Low-pass + EMA
Switches / ButtonsDebouncing + Median
Noisy digital signalSchmitt Trigger + Median

 Best Practices

  • Sample faster than signal changes (oversampling helps filtering).

  • Apply anti-aliasing filters before ADC for analog signals.

  • Filter only when needed — avoid excessive smoothing that delays response.

  • Consider multi-stage filters: hardware + software combo for critical applications.

评论

此博客中的热门博文

Detailed Explanation of STM32 HAL Library Clock System

How To Connect Stm32 To PC?

How to add a GPS sensor to ESP32 for Wokwi?