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)]

 

UK Electronic Designer
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.