IIR filter

15 May 2014

Hi, I am trying to make an IIR filter to filter out 48.5 - 51.5Hz. I was given the following code as an example:

#include "mbed.h"
 
AnalogIn Ain(p15);
AnalogOut Aout(p18);
 
Ticker s20khz_tick;
 
void s20khz_task(void);
 
float data_in, data_out;
 
float LPF(float LPF_in){
 
float a[4]={1,2.623551806,-2.3146825811,0.6855359773};
float b[4]={0.0006993496,0.0020980489,0.0020980489,0.0006993496};
 
static float LPF_out;
static float x[4],y[4];
 
x[3] = x[2];x[2]=x[1];x[1]=x[0];
y[3]=y[2];y[2]=y[1];y[1]=y[0];
 
x[0]=LPF_in;
y[0]=LPF_in;
y[0]=(b[0]*x[0]) + (b[1]*x[1]) +(b[2]*x[2]) + (b[3]*x[3]) + (a[1]*y[1]) + (a[2]*y[2]) + (a[3]*y[3]);
 
LPF_out = y[0];
return LPF_out;
}
 
void s20khz_task(void){
data_in=Ain;
data_out=LPF(data_in);
Aout=data_out;
}
 

int main() {
    s20khz_tick.attach_us(&s20khz_task,50);
    while(1);
}

. . Now using MATLAB as shown here:

/media/uploads/lanfear/fdatool_iir_notch_v2.png . The coefficients were gotten. However since it is a 2nd order I changed the program like this :

#include "mbed.h"
 
AnalogIn Ain(p20);
AnalogOut Aout(p18);
 
Ticker s20khz_tick;
 
void s20khz_task(void);
 
float data_in, data_out;
 
float LPF(float LPF_in)
{
 
float a[3]={1,-1.6026601844431179,0.98099693280404443};
float b[3]={0.99049846640202222,-1.6026601844431179, 0.99049846640202222};
 
static float LPF_out;
static float x[3],y[3];
 
x[2]=x[1]; x[1]=x[0];
y[2]=y[1]; y[1]=y[0];
 
x[0]=LPF_in;
y[0]=LPF_in;
y[0]=(b[0]*x[0]) + (b[1]*x[1]) +(b[2]*x[2]) + (a[1]*y[1]) + (a[2]*y[2]) ;
 
LPF_out = y[0];
return LPF_out;
}
 
void s20khz_task(void)
{
data_in=Ain;
data_out=LPF(data_in);
Aout=data_out;
}
 

int main() 
{
    s20khz_tick.attach_us(&s20khz_task,50);
    while(1);
}

Problem is that it still doesnt seem to work. Any one have any ideas why?

Thanks in advanced Johann

26 May 2014

In your program you specify a sampling time of 50us (20kHz sampling rate) but in your design program you specify 500Hz sampling rate. A factor of 40, does it filter out 2000Hz?

08 Nov 2016
  1. include "mbed.h"

AnalogIn Ain(p15); AnalogOut Aout(p18);

Ticker s20khz_tick;

void s20khz_task(void);

float data_in, data_out;

float LPF(float LPF_in){

float a[4]={1,2.623551806,-2.3146825811,0.6855359773}; float b[4]={0.0006993496,0.0020980489,0.0020980489,0.0006993496};

static float LPF_out; static float x[4],y[4];

x[3] = x[2];x[2]=x[1];x[1]=x[0]; y[3]=y[2];y[2]=y[1];y[1]=y[0];

x[0]=LPF_in; y[0]=LPF_in; y[0]=(b[0]*x[0]) + (b[1]*x[1]) +(b[2]*x[2]) + (b[3]*x[3]) + (a[1]*y[1]) + (a[2]*y[2]) + (a[3]*y[3]);

LPF_out = y[0]; return LPF_out; }

void s20khz_task(void){ data_in=Ain; data_out=LPF(data_in); Aout=data_out; }

int main() { s20khz_tick.attach_us(&s20khz_task,50); while(1); }

using matlab too?