Simple signal processing in C#
c#, signal-processing
Solution
You always need to store some values (but not necessarily all input values). A filter's current output depends on a number of input values and possibly some past output values.
The simplest filter would be a first order Butterworth low-pass filter. This would only require you to store one past output value. The (current) output of the filter, y(n) is:
y(n) = x(n) - a1 * y(n-1)
where x(n) is the current input and y(n-1) is the previous output of the filter. a1 depends on the cut-off frequency and the sampling frequency. The cut-off frequency frequency must be less than 5 Hz (half the sampling frequency), sufficiently low to filter out the noise, but not so low that the output will be delayed with respect to the input. And of course not so low that the real signal is filtered out!
In code (mostly C#):
double a1 = 0.57; //0.57 is just an example value.
double lastY = 0.0;
while (true)
{
double x = <get an input value>;
double y = x - a1 * lastY;
<Use y somehow>
lastY = y;
}
Whether a first order filter is sufficient depends on your requirements and the characteristics of the input signal (a higher order filter may be able to suppress more of the noise at the expense of higher delay of the output signal).
For higher order filters, more values would have to be stored and the code becomes a little bit more complicated. Usually the values need to be shifted down in arrays; in an array for past y values and in an array for past x values.
Problem
I'm sampling a real-world sensor, and I need to display its filtered value. The signal is sampled at a rate of 10 Hz and during that period it could rise as much as 80 per cent of the maximum range. Earlier I've used Root Mean Square as a filter and just applying it to the last five values I've logged. For this application this wouldn't be good because I don't store unchanged values. In other words, I need to consider time in my filter... I've read at DSP Guide, but I didn't get much out of it. Is there a tutorial that's pinned specifically at programmers, and not Mathcad engineers? Are there some simple code snippets that could help? Update: After several spreadsheet tests I've taken the executive decision to log all samples, and apply a Butterworth filter.