A visualised example of a averaging filter applied to noisy data. Jagged blue line represents raw data. Smooth, superimposed black curve represents averaged filter. Image: http://www.biomecardio.com/matlab/sffilt.html
Filters are integral to working with sensors, and especially sensors that are naturally prone to high levels of fluctuation, i.e. noise. You can often see this when you trace the output of a noisy analogue reading to the Serial Port.
Examples of ‘noisy’ analogue sensors:
Audio microphones
Distance/proximity sensors
LDRs (light-dependent resistors)
FSRs (force-sensitive resistors)
How do we ‘massage’ these raw sensor values to get a smoother response over time? We can implement signal filters in code. For the purpose of this studio, let's look at the most basic, but highly effective Simple Moving Average (SMA) filter.
Here's a summary of what this filter does:
Store the last n number of readings of the sensor into an array (i.e. a list of numbers stored in memory)
Find the average of these n readings – and use this averaged reading
Continue to maintain the last n number of readings constantly (hence moving average)
Repeat from step 2
It will therefore make sense that the size of the array, i.e. n, will impact the rate of change of the averaged reading. A higher n value will result in slower, less-responsive sensor reading but one that is extremely stable. Depending on your sensor and application scenario, you will then experiment with raising/lowering this n value to strike the right balance between responsiveness and stability.
Note that you can also design some filters using hardware (look for RC or LC circuits as an example), instead of writing code. The benefit of hardware filters is zero coding, but a deeper understanding of electrical characteristics of inductors, resistors and capacitors are required. This recipe will focus on software signal filters that we can run on the Photon.
Figure out how to use the above code snippet into your existing project. Noisy sensor no more!