A median filter is a type of FIR filter which typically takes an odd number of inputs (e.g. 5 or more usually more) and sorts them by value. The filtered output is the median value (the middle value). A median filter can be very effective at removing noise spikes.
Example Code
Start New Filter Sequence
#define MEDIAN_FILTER_NO_OF_READINGS 512
WORD count;
static WORD filter_current_count;
static WORD filter_buffer[MEDIAN_FILTER_NO_OF_READINGS];
//START NEW FILTER SEQUENCE
filter_current_count = 0;
for (count = 0; count < MEDIAN_FILTER_NO_OF_READINGS; count++)
filter_buffer[count] = 0;
Add Next Reading
//ADD NEXT READING
//w_temp is the new reading value to add
//Move through the buffer from the last current entry and add this reading in its correct value ordered position
for (count = filter_current_count; count <= filter_current_count; count--)
{
if (count > 0)
{
if (filter_buffer[(count - 1)] < w_temp)
{
filter_buffer[count] = w_temp;
break;
}
filter_buffer[count] = filter_buffer[(count - 1)];
}
else
{
filter_buffer[count] = w_temp; //This is a new lowest value to add at the bottom of the buffer
break;
}
}
filter_current_count++;
Get the Median Result
//GET MEDIAN RESULT
value_to_use = filter_buffer[(MEDIAN_FILTER_NO_OF_READINGS / 2)]
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.