四阶IIR滤波器c代码实现

一,通过matlab获取4阶IIR系数

matlab filterDesigner获取滤波器系数

 

二,编写C代码实现滤波

#define double sample_t

typedef struct
{
	sample_t gain;
	sample_t a1, a2, a3, b1, b2, b3;
	sample_t x1, x2, y1, y2;
}mult_biquad_state;

sample_t mult_biquad(mult_biquad_state *state, sample_t data)
{
	sample_t result = 0.0;
	result = state->gain * (state->b1 * data + state->b2 * state->x1 + state->b3 * state->x2) - state->a2 * state->y1 - state->a3 * state->y2;
	result = result / state->a1;
	state->x2 = state->x1;
	state->x1 = data;
	state->y2 = state->y1;
	state->y1 = result;
	return result;
}

int main(int argc, char **argv) 
{
    int numbers = 1024;
   sample_t data[numbers], result[numbers]; mult_biquad_state *mult_stat1 = (mult_biquad_state *) malloc(sizeof(mult_biquad_state)); mult_biquad_state *mult_stat2 = (mult_biquad_state *) malloc(sizeof(mult_biquad_state)); mult_stat1->gain = 0.000050472384297472574804684086746675575; mult_stat1->b1 = 1, mult_stat1->b2 = 2, mult_stat1->b3 = 1; mult_stat1->a1 = 1, mult_stat1->a2 = -1.98895297844260232622559669835027307272, mult_stat1->a3 = 0.989154867979792129517591092735528945923; mult_stat1->x1 = 0 ,mult_stat1->x2 = 0, mult_stat1->y1 = 0, mult_stat1->y2 = 0; mult_stat2->gain = 0.000050088274033639684855011980912919967; mult_stat2->b1 = 1, mult_stat2->b2 = 2, mult_stat2->b3 = 1; mult_stat2->a1 = 1, mult_stat2->a2 = -1.9738164386508996184232955783954821527, mult_stat2->a3 = 0.974016791747034260673387962015112861991; mult_stat2->x1 = 0 ,mult_stat2->x2 = 0, mult_stat2->y1 = 0, mult_stat2->y2 = 0; for (int i = 0; i <numbers; ++i) {  data[i] = 0.5 * (sin(2 * PI * 40 * i / fs) + cos(2 * PI * 150 * i / fs + PI / 4)); } for (int i = 0; i <numbers; ++i) { result[i] = mult_biquad(mult_stat1, data[i]); result[i] = mult_biquad(mult_stat2, result[i]); } free(mult_stat1); free(mult_stat2); }

  

 

posted @ 2020-12-02 18:01  繁华如梦个人笔记  阅读(1308)  评论(0编辑  收藏  举报