Hi Madhura,
Since I don't know the purpose of your filter, I can't suggest which one would be better. If you are using it for a control application, the exponential filter would likely be better (faster step-response and smoother transitions). If you are using it for numerical analysis, the boxcar filter may be better. If you need the filter for decimation, both would work, but I would lean toward the boxcar.
All of my code is written in assembler, for the DSP563xx of for the HC08/S08. But since the exponential filter is so simple to implement in C, here is some code (not verified for syntax):
static float coefficient; // 0 through 1 for how much filtering to do
/*
This function implements an exponential filter
on a sample, returning the filtered value.
*/
float filter( float sample )
{
static float result;
result = coefficient*sample + (1-coefficient)*result
return result;
}
/*
This function sets the strength of the filter, and
has a valid range of zero to one. A one will not filter
at all, returning the sample unmodified, and a zero
will freeze the result at its current value.
If the new coefficient is outside of the valid range,
then it will remain unmodified.
*/
void setCoefficient ( float newCoefficient )
{
if ( newCoefficient >= 0 ) && ( newCoefficient <= 1 )
coefficient = newCoefficient;
}If you would like the filter to respond similarly to an average of eight samples, then you would want to set the coefficient to one-eighth (1/8, 0r 0.125). With the exponential filter, the filter coefficient can be changed on-the-fly.
If you need a true average, then that code would need a static array of the most recent samples, operated as a ring-buffer. You would also need the ring-buffer index to be static. Rather than adding all samples and the dividing by the number of samples, you should keep a static copy of the first result, and then simply subtract-out the oldest sample and add-in the newest sample with each new sample.
Hope that helps.
Mark