CPlay/fir.c
2025-08-20 09:49:36 +02:00

42 lines
1.1 KiB
C

#include <stdio.h>
#define N 5 // Number of taps (filter coefficients)
// Example filter coefficients (simple low-pass averaging filter)
float coeffs[N] = {
0.2, 0.2, 0.2, 0.2, 0.2 // Equal weights → moving average filter
};
float buffer[N] = {0}; // Circular buffer to store recent inputs
int bufIndex = 0;
float fir_filter(float input) {
buffer[bufIndex] = input;
float output = 0.0;
int index = bufIndex;
// Apply the convolution (dot product of input buffer and coefficients)
for (int i = 0; i < N; ++i) {
output += coeffs[i] * buffer[index];
if (--index < 0)
index = N - 1; // Wrap around circular buffer
}
bufIndex = (bufIndex + 1) % N;
return output;
}
int main() {
float noisy_signal[] = {1, 2, 3, 2,
100, 3, 2, 1}; // A spike in the middle (100)
int len = sizeof(noisy_signal) / sizeof(float);
printf("Filtered output:\n");
for (int i = 0; i < len; ++i) {
float filtered = fir_filter(noisy_signal[i]);
printf("%.2f\n", filtered);
}
return 0;
}