You are on page 1of 4

A Quick and Dirty Realtime Digital (IIR/FIR)

Filter Implementation
MAY 31ST, 2013 | COMMENTS

Introduction
You have this Data Acquisition System that coughs out data in
real time, and you want to add a digital filter that takes each
filter sample, throws out the filtered output. Thats the task of
this post.
Lets say the digital data is over your computers serial port, and
you have set up some Matlab code to plot it already, now we
need to filter each sample before storing it for plotting.
First of all you need to decide what kind of filter you want to use
low pass/bandpass etc, butterworth/elliptic etc, the filters
order, cutoff frequency etc. And depending on all that use the
matlab functions like butter(), ellip() to get the coefficients of the
filter you want to use. You could calculate the coefficients by any
other method also. This post assumes that you already have the
filter coefficients and you just need some simple code to
implement the filter.
Now that you have the coefficients usually denoted by the
vectors a and b for the denominator and numerator
respectively, lets look at the general form of an IIR filter

H(z)=Pi=0bizi1+Qj=1ajzj
Make sure that in your coefficients, a(0)=1.

Use the following code to implement the above filter:


1[b_lp,a_lp] = butter(8,40/(Fs/2),'low');
2global dbuffer ;
3dbuffer = zeros(length(b_lp),1); % buffer for LPF
4%....... Read the ADC value from the serialport...
5% Pass it to the filter subfunction
6filtered_value = NewFilter(b_lp, a_lp, value);
7%..... Plot data....
8
9% NewFilter subfunction
1function [data] = NewFilter(b, a,value)
0k = 1;
1global dbuffer ;
1while(k<length(b))
1dbuffer(k) = dbuffer(k+1);
2k=k+1;
1end
3dbuffer(length(b)) = 0;
1k = 1;
4while(k<(length(b)+1))
1dbuffer(k) = dbuffer(k) + value * b(k);
5k=k+1;
1end
6
1k = 1;
7while(k<length(b))
1dbuffer(k+1) = dbuffer(k+1) - dbuffer(1) * a(k+1);
8k=k+1;
1end
9
2data = dbuffer(1);
0
2
1
2
2

2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0

Thats all to it! Now consider an FIR filter, this is easier because
now we do not have the vector a , so just delete the Multiply and
accumulate loop for the a terms in the above code.
A moving average filter can also be implemented in a similar
fashion. The code looks like this:
1function [data] = MavgFilter(value)
2
3k = 1;
4global Dbuffer ;
5global N;
6% 1. shift by one element (discard the left most element)
7while(k<N)
8Dbuffer(k) = Dbuffer(k+1);
9k=k+1;
1end
0Dbuffer(N) = 0;
1
1k = 1;

1
2
1
3
1
4while(k<N+1)
1Dbuffer(k) = Dbuffer(k) + value;
5k=k+1;
1end
6
1data = Dbuffer(1)/N;
7
1
8
1
9

Obviously, the same code can be used in any other language


like C, or C# if you want to do analysis using them. And also
note that this is not the most efficient implementation, but its
easy to understand and quick to implement, so its always good
for a first try.
http://www.desultoryquest.com/blog/a-quick-and-dirty-real-time-digital-iir-slashfir-filter-implementation/

You might also like