如何用C语言写4阶巴特沃斯高通滤波器,要求输入输出均为长整型
时间: 2024-03-17 15:41:16 浏览: 70
巴特沃斯高通滤波器是一种数字滤波器,用于滤除低频信号并保留高频信号。4阶的巴特沃斯高通滤波器具有更陡峭的通带边缘和更窄的过渡带,可以更好地滤除低频信号。下面是一个用C语言实现4阶巴特沃斯高通滤波器的示例代码,输入输出均为长整型:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define M_PI 3.14159265358979323846
long b[5]; // 分子系数
long a[5]; // 分母系数
long x[5]; // 输入信号
long y[5]; // 输出信号
void butterworth_highpass_filter_4th_order(long fc, int fs, double Q)
{
double w0 = 2 * M_PI * fc / fs;
double alpha = sin(w0) / (2 * Q);
double cosw0 = cos(w0);
double alpha2 = alpha * alpha;
double beta = sqrt(alpha2 + cosw0 * cosw0 - 2 * alpha * cosw0);
double gamma = alpha2 + cosw0 * beta + alpha;
b[0] = (long)(alpha2 * pow(2, 30) / gamma);
b[1] = (long)(2 * alpha2 * pow(2, 30) / gamma);
b[2] = (long)(alpha2 * pow(2, 30) / gamma);
b[3] = (long)(-2 * alpha2 * pow(2, 30) / gamma);
b[4] = (long)(alpha2 * pow(2, 30) / gamma);
a[0] = pow(2, 30) + (long)(alpha * pow(2, 30));
a[1] = (long)(-2 * pow(2, 30) * cosw0);
a[2] = pow(2, 30) - (long)(alpha * pow(2, 30));
a[3] = (long)(-2 * pow(2, 30) * cosw0);
a[4] = pow(2, 30) - (long)(alpha2 * pow(2, 30) / gamma);
double gain = 1 / (double)a[0];
b[0] = (long)(b[0] * gain);
b[1] = (long)(b[1] * gain);
b[2] = (long)(b[2] * gain);
b[3] = (long)(b[3] * gain);
b[4] = (long)(b[4] * gain);
a[1] = (long)(-a[1]);
a[3] = (long)(-a[3]);
a[4] = (long)(-a[4]);
x[0] = x[1] = x[2] = x[3] = x[4] = 0;
y[0] = y[1] = y[2] = y[3] = y[4] = 0;
}
long butterworth_highpass_filter_4th_order_apply(long input)
{
x[4] = x[3];
x[3] = x[2];
x[2] = x[1];
x[1] = x[0];
x[0] = input;
y[4] = y[3];
y[3] = y[2];
y[2] = y[1];
y[1] = y[0];
y[0] = (long)((b[0] * x[0] + b[1] * x[1] + b[2] * x[2] + b[3] * x[3] + b[4] * x[4] - a[1] * y[1] - a[3] * y[3] - a[4] * y[4]) / (double)a[0]);
return y[0];
}
int main()
{
long fc = 1000; // 截止频率为1kHz
int fs = 8000; // 采样率为8kHz
double Q = 0.707; // 质因数Q为0.707
butterworth_highpass_filter_4th_order(fc, fs, Q);
// 生成测试信号,1s的8000Hz正弦波
int num_samples = 8000;
long test_signal[num_samples];
for (int i = 0; i < num_samples; i++) {
test_signal[i] = (long)(sin(2 * M_PI * i * 1000 / fs) * pow(2, 30));
}
// 对测试信号进行滤波
long filtered_signal[num_samples];
for (int i = 0; i < num_samples; i++) {
filtered_signal[i] = butterworth_highpass_filter_4th_order_apply(test_signal[i]);
}
// 将结果输出到文件
FILE *fp = fopen("filtered_signal.txt", "w");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
for (int i = 0; i < num_samples; i++) {
fprintf(fp, "%ld\n", filtered_signal[i]);
}
fclose(fp);
return 0;
}
```
在这个示例中,我们首先定义了一个 `butterworth_highpass_filter_4th_order` 函数,用于计算4阶巴特沃斯高通滤波器的分子和分母系数。然后,我们定义了一个 `butterworth_highpass_filter_4th_order_apply` 函数,用于对输入信号进行滤波。在 `main` 函数中,我们首先生成了一个1秒钟的正弦波作为测试信号,然后对其进行滤波,并将结果输出到文件中。
需要注意的是,在这个示例中,我们将输入信号和输出信号都乘以了 $2^{30}$,以避免在计算过程中出现浮点运算误差。在使用时,需要根据具体的需求进行修改。
阅读全文