c++实现巴特沃斯带通滤波器
时间: 2023-05-30 16:07:50 浏览: 97
c++巴特沃斯数字滤波器
巴特沃斯带通滤波器是一种数字信号处理滤波器,可以通过将频率范围限制在一定的带宽内来滤除信号中的噪声或其他干扰。它是一种IIR滤波器,通常由一个或多个二阶滤波器级联而成。
以下是C语言实现巴特沃斯带通滤波器的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846
// 二阶滤波器结构体定义
typedef struct {
double a1, a2, b0, b1, b2; // IIR滤波器系数
double x1, x2, y1, y2; // 过去的输入/输出样本值
} Filter2nd;
// 初始化二阶滤波器
void initFilter2nd(Filter2nd *filt, double fs, double f1, double f2) {
double omega1 = 2 * PI * f1 / fs;
double omega2 = 2 * PI * f2 / fs;
double c1 = cos(omega1);
double c2 = cos(omega2);
double s1 = sin(omega1);
double s2 = sin(omega2);
double alpha = s1 * s2 / (c1 * c2 + s1 * s2);
filt->b0 = alpha;
filt->b1 = 0;
filt->b2 = -alpha;
filt->a1 = 2 * (c1 * c2 - s1 * s2) / (c1 * c2 + s1 * s2);
filt->a2 = -(c1 * c2 + s1 * s2) / (c1 * c2 + s1 * s2);
filt->x1 = 0;
filt->x2 = 0;
filt->y1 = 0;
filt->y2 = 0;
}
// 单个样本点的二阶滤波器处理
double filterSample2nd(Filter2nd *filt, double x) {
double y = filt->b0 * x + filt->b1 * filt->x1 + filt->b2 * filt->x2
- filt->a1 * filt->y1 - filt->a2 * filt->y2;
filt->x2 = filt->x1;
filt->x1 = x;
filt->y2 = filt->y1;
filt->y1 = y;
return y;
}
// 实现巴特沃斯带通滤波器
void butterworthBandpassFilter(double *input, double *output, int length, double fs, double f1, double f2, int order) {
Filter2nd *filt = (Filter2nd *) malloc(sizeof(Filter2nd) * order);
for (int i = 0; i < order; i++) {
initFilter2nd(&filt[i], fs, f1, f2);
}
for (int i = 0; i < length; i++) {
double x = input[i];
for (int j = 0; j < order; j++) {
x = filterSample2nd(&filt[j], x);
}
output[i] = x;
}
free(filt);
}
int main() {
double fs = 1000; // 采样率
double f1 = 10; // 通带下限频率
double f2 = 50; // 通带上限频率
int order = 4; // 滤波器阶数
// 生成测试信号
int length = 1000;
double *input = (double *) malloc(sizeof(double) * length);
double *output = (double *) malloc(sizeof(double) * length);
for (int i = 0; i < length; i++) {
double t = (double) i / fs;
input[i] = sin(2 * PI * 20 * t) + 0.5 * sin(2 * PI * 100 * t) + 0.2 * sin(2 * PI * 200 * t);
}
// 进行滤波处理
butterworthBandpassFilter(input, output, length, fs, f1, f2, order);
// 输出结果到文件
FILE *fp = fopen("output.txt", "w");
for (int i = 0; i < length; i++) {
fprintf(fp, "%f\n", output[i]);
}
fclose(fp);
free(input);
free(output);
return 0;
}
```
该代码中实现了一个二阶滤波器结构体`Filter2nd`和初始化函数`initFilter2nd`,以及单个样本点的滤波函数`filterSample2nd`。然后通过`butterworthBandpassFilter`函数实现了对输入信号的带通滤波处理。具体实现方式是对每个样本点依次通过多个二阶滤波器进行处理,得到最终的输出信号。最后将结果输出到文件中。
阅读全文