Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIR filter implementation in C programming

Can anyone tell me how to implement an FIR filter using c programming language.

like image 813
D X Avatar asked Jan 17 '26 08:01

D X


1 Answers

Designing an FIR filter is NOT a simple topic, but implementing an already-designed filter (assuming you already have the FIR coefficients) isn't too bad. The algorithm is called convolution. Here's a naive implementation...

void convolve (double *p_coeffs, int p_coeffs_n,
               double *p_in, double *p_out, int n)
{
  int i, j, k;
  double tmp;

  for (k = 0; k < n; k++)  //  position in output
  {
    tmp = 0;

    for (i = 0; i < p_coeffs_n; i++)  //  position in coefficients array
    {
      j = k - i;  //  position in input

      if (j >= 0)  //  bounds check for input buffer
      {
        tmp += p_coeffs [i] * p_in [j];
      }
    }

    p_out [k] = tmp;
  }
}

Basically, the convolution does a moving weighted average of the input signal. The weights are the filter coefficients, which are assumed to sum to 1.0. If the weights sum to something other than 1.0, you get some amplification/attenuation as well as filtering.

BTW - it's possible this function has the coefficients array backwards - I haven't double-checked and it's a while since I thought about these things.

For how you calculate the FIR coefficients for a particular filter, there's a fair amount of mathematics behind that - you really need a good book on digital signal processing. This one is available free for a PDF, but I'm not sure how good it is. I have Rorabaugh and Orfandis, both published in the mid nineties but these things don't really get obsolete.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!