0

I need to implement a transfer function from direct form II. Here's a description of what direct form II is. I'm allowed to choose what coefficents are to be included.

So far my code looks like this:

int main(void)
{
    int l, m;
    l = dirii2(2); // l = -82;
    //m = directii(2);

    return l;
}

int dirii2(int x)
{
    int y = 0; // output    // 3 is constant of array size.
    static int  v[3] = {6,4,0};
    int b[3] = {3,5,2}, a[2] = {3,6};
    int q0, q1, q2;

    for (int i = 0; i < 3 ; i++) {
        q0 = x; // q0 = x = 2
        q1 = a[2-2]*v[2-1]; // q1 = 3 * 6 = 18
        q2 = a[2-1]*v[2-2]; // q2 = 6 * 4 = 24
        v[2] = q0 - q1 - q2;//  v(n) = x(n) - a1*v(n-1) - a2v(n-2);  // v = 2 - 18 - 24 = -40
        y =+ b[i]*v[2-i];// + b[1]*v[2-1]+b[2]*v[2-2];
        v[0] = v[1];
        v[1] = v[2];
    }
    return y;
}

When I run the code the result y gains or loses values rapidly like it's getting unstable:

  1. First iteration y becomes -138.
  2. Second iteration y becomes 230.
  3. Third iteration y becomes -92.

Did I write the code right?

user3386109
  • 34,287
  • 7
  • 49
  • 68
  • 1
    Note `=+` is old style (pre-K&R). Did you mean `+=` ? – wildplasser Apr 22 '20 at 19:25
  • From [this article](https://en.wikipedia.org/wiki/Digital_filter#Direct_form_II): *"The disadvantage is that direct form II increases the possibility of arithmetic overflow for filters of high Q or resonance."* So I don't think you can just randomly pick coefficients. You need to pick coefficients that result in a reasonable value for Q. – user3386109 Apr 22 '20 at 19:28
  • oh, yea this is a minor mistake, but... ok. –  Apr 22 '20 at 19:40
  • so here's the thing, is the code written correctly? Because I think this is bigger issue than choosing the coefficients –  Apr 22 '20 at 19:42
  • An no, i am not making a filter, just how to implement in C –  Apr 22 '20 at 19:42

0 Answers0