How to filter noise from sensor

How to filter noise from sensor reading in Arduino code?

Answer

The reading value from sensors may includes noise, especially for analog sensor or environment-sensitive sensor such as ultrasonic sensor. You can use the below method to remove the noised values.

How to filter noise from sensor measurement

The measurement result from some kinds of sensor contains noise. In some application, the noised result causes the unwanted operation. We can remove noise by using the following method:

  1. Taking multiple measurements and store them in an array
  2. Sorting the array in ascending or descending order
  3. Filtering noise
    • The some smallest samples are considered as noise ⇒ ignore them
    • The some biggest samples are considered as noise ⇒ ignore them
    • ⇒ get average of the middle samples

    The below example code takes 20 measurements

    • The five smallest samples are considered as noise → ignore it
    • The five biggest samples are considered as noise → ignore it
    • ⇒ get average of the 10 middle samples (from 5th to 14th)
    /* * Created by ArduinoGetStarted.com * * This example code is in the public domain * * Tutorial page: https://arduinogetstarted.com/faq/how-to-filter-noise-from-sensor */ int filterArray[20]; // array to store data samples from sensor void setup() { // begin serial port Serial.begin (9600); } void loop() { // 1. TAKING MULTIPLE MEASUREMENTS AND STORE IN AN ARRAY for (int sample = 0; sample < 20; sample++) { filterArray[sample] = analogRead(A0);; delay(5); } // 2. SORTING THE ARRAY IN ASCENDING ORDER for (int i = 0; i < 19; i++) { for (int j = i + 1; j < 20; j++) { if (filterArray[i] > filterArray[j]) { int swap = filterArray[i]; filterArray[i] = filterArray[j]; filterArray[j] = swap; } } } // 3. FILTERING NOISE // + the five smallest samples are considered as noise -> ignore it // + the five biggest samples are considered as noise -> ignore it // ---------------------------------------------------------------- // => get average of the 10 middle samples (from 5th to 14th) long sum = 0; for (int sample = 5; sample < 15; sample++) { sum += filterArray[sample]; } int avg_value = sum / 10; // print the value to Serial Monitor Serial.print("average value: "); Serial.println(avg_value); }

    Buy Arduino

    1 × Arduino UNO Buy on Amazon
    1 × USB 2.0 cable type A/B Buy on Amazon
    1 × Jumper Wires Buy on Amazon
    Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

The Best Arduino Starter Kit

※ OUR MESSAGES