c++实现巴特沃斯带通滤波器代码
时间: 2023-06-02 12:01:37 浏览: 69
巴特沃斯滤波的C语言实现
3星 · 编辑精心推荐
巴特沃斯带通滤波器是一种常见的数字信号处理滤波器,可以用于滤除某些频率范围内的噪声信号,保留其他频率范围内的信号。下面是一份C语言实现的巴特沃斯带通滤波器代码示例:
```c
#include <math.h>
#define PI 3.14159265358979323846
typedef struct {
int order; // 阶数
float fc1; // 通带截止频率1
float fc2; // 通带截止频率2
float fs; // 采样频率
float a[10]; // 系数a
float b[10]; // 系数b
} ButterworthFilter;
void butterworth_bandpass_init(ButterworthFilter *filter, int order, float fc1, float fc2, float fs) {
filter->order = order;
filter->fc1 = fc1;
filter->fc2 = fc2;
filter->fs = fs;
float W1 = 2 * PI * fc1 / fs;
float W2 = 2 * PI * fc2 / fs;
float alpha1 = sin(W1) / (2 * order);
float alpha2 = sin(W2) / (2 * order);
float beta = cos((W1 + W2) / 2) / 2;
float gamma = 1 / tan((W2 - W1) / 2);
float a0 = 1 + alpha1;
float b0 = 1 + alpha2;
for (int i = 0; i < order; i++) {
filter->a[i] = 2 * cos((2 * i + 1) * PI / (2 * order)) / a0;
filter->b[i] = 2 * cos((2 * i + 1) * PI / (2 * order)) / b0;
}
filter->a[order] = (1 - alpha1) / a0;
filter->b[order] = (1 - alpha2) / b0;
filter->a[order + 1] = -beta * gamma / a0;
filter->b[order + 1] = beta * gamma / b0;
filter->a[order + 2] = -(1 - alpha1) / a0;
filter->b[order + 2] = -(1 - alpha2) / b0;
filter->a[order + 3] = 0;
filter->b[order + 3] = 0;
}
float butterworth_bandpass_filter(ButterworthFilter *filter, float input) {
float output = input;
for (int i = 0; i < filter->order; i++) {
float temp = output;
output = filter->a[i] * output + filter->b[i] * filter->a[filter->order + i] - filter->b[filter->order + i] * filter->a[filter->order + i] + filter->b[filter->order + i] * temp;
}
return output;
}
```
使用方法:
```c
int main() {
ButterworthFilter filter;
butterworth_bandpass_init(&filter, 4, 50, 100, 1000);
float input = 0.0;
float output = 0.0;
for (int i = 0; i < 1000; i++) {
output = butterworth_bandpass_filter(&filter, input);
input = sin(2 * PI * 50 * i / 1000) + sin(2 * PI * 100 * i / 1000);
printf("%f\n", output);
}
return 0;
}
```
在上面的例子中,初始化了一个4阶、通带截止频率为50Hz至100Hz、采样频率为1000Hz的巴特沃斯带通滤波器,并将输入信号设置为50Hz和100Hz的正弦波信号。使用`butterworth_bandpass_filter`函数对输入信号进行滤波,并打印输出信号。
阅读全文