用C语言实现一阶巴特沃斯高通滤波器
时间: 2023-05-17 15:05:59 浏览: 140
可以使用以下代码实现一阶巴特沃斯高通滤波器:
```c
#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
double b0, b1, b2, a1, a2;
void butterworth_highpass(double fc, double fs, int order) {
double wc = tan((PI * fc) / fs);
double k = wc / (1 + wc);
double k2 = k * k;
double sqrt2 = sqrt(2.0);
double sqrt2k = sqrt2 * k;
double sqrt2k2 = sqrt2 * k2;
double sqrt2kk2 = sqrt2 * k * k2;
double sqrt2k2k2 = sqrt2 * k2 * k2;
switch (order) {
case 1:
b0 = k;
b1 = -k;
a1 = -k + 1;
break;
case 2:
b0 = k2;
b1 = -2 * k2;
b2 = k2;
a1 = -2 * k + 2;
a2 = -k2 + 2 * k - 1;
break;
case 3:
b0 = k2 * sqrt2k;
b1 = -2 * k2 * sqrt2k;
b2 = k2 * sqrt2k;
a1 = -2 * k * (1 + sqrt2k + k2);
a2 = -(1 + sqrt2k2 + sqrt2kk2 + sqrt2k2k2);
break;
default:
printf("Unsupported order %d\n", order);
break;
}
}
double filter(double x) {
static double x1 = 0, x2 = 0, y1 = 0, y2 = 0;
double y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
x2 = x1;
x1 = x;
y2 = y1;
y1 = y;
return y;
}
int main() {
double fc = 1000; // 我们要实现的截止频率
double fs = 44100; // 采样率
int order = 2; // 阶数
butterworth_highpass(fc, fs, order);
// 现在我们可以使用 filter 函数来过滤信号了
return 0;
}
```
这段代码实现了一个一阶、二阶或三阶的巴特沃斯高通滤波器,可以通过调整 `fc` 和 `order` 参数来控制截止频率和阶数。
阅读全文