Skip to main content

Microcontrollers

Section 7.3 Mitigating Fluctuating Data and Sensor Noise

Sensor data can fluctuate over time due to environmental conditions or noise. It may be important to perform a rolling average to obtain a steady, reliable readout. A rolling average uses \(n\) previous values (stored in an array) to calculate the current average value. Care must be taken in choosing an appropriate value for \(n\text{,}\) which must be specifically tailored to each different sensor and situation in which it is to be used. If \(n\) is small,
If \(n\) is large,
  • more data memory is needed to store sensor values,
  • the program will require more time to initialize,
  • the output value will be less susceptible to sensor noise, and
  • if \(n\) is too large, the output will not be sensitive to short-term or quick changes in sensor values.
Sensor data from a temperature sensor that has been averaged out using three different values of \(n\) (as well as the raw data, which has an \(n\) value of 1) is shown in FigureΒ 7.3.1.
Graph of temperature data plotted with respect to time. The data fluctuates a lot when n = 1. It is smoother when n = 5, even smoother when n = 20, and the most smooth when n = 40.
Figure 7.3.1. Temperature data subjected to rolling average with different values of \(n\text{.}\)

Subsection 7.3.1 Circular Buffer

A circular buffer is a method of taking a rolling average to clean up sensor noise and fluctuations. It is simply an array of \(n\) sensor values, where the first value in is also the first value out. (This type of situation is known as FIFO: first in first out.) A sample array of data is shown in FigureΒ 7.3.2 to depict this process.
Example data shown in a circular buffer changing over several iterations of data collection.
Figure 7.3.2. Example array of values stored in a circular buffer. New values overwriting old ones are depicted in red.
The data in the circular buffer can be pointed to in a subroutine and averaged to determine the average over the given timespan.

Subsection 7.3.2 Timed Updates

Instead of retrieving continuous updates from the sensor, the sensor value can be updated only at finite, regularly spaced intervals of time. This can be accomplished using timed interrupts. The concept of interrupts is explained in ChapterΒ 8, and the timer/counter units are explained in ChapterΒ 9.
For maximum noise filtering, this method can be combined with the circular buffer method.