Arduino-FOC icon indicating copy to clipboard operation
Arduino-FOC copied to clipboard

[BUG] LowPassFilter returns wrong values at startup

Open sylque opened this issue 1 year ago • 2 comments
trafficstars

Not sure what kind of actual impact this might have on the rest of the library, but I believe there is something wrong in the LowPassFilter class:

LowPassFilter::LowPassFilter(float time_constant)
    : ...
    , y_prev(0.0f)
{
    ...
}


float LowPassFilter::operator() (float x)
{
    ...
    float y = alpha*y_prev + (1.0f - alpha)*x;
    y_prev = y;
	...
    return y;
}

Because y_prev is initialized to zero, the first calls to operator() returns the wrong result. At the first call, y_prev should probably be initialized with x instead of zero. In other words, the first call to LowPassFilter(5) should return 5 and not a weighted average of 5 with zero.

Notice that, in LowPassFilter::operator(), you can also see:

if(dt > 0.3f) {
        y_prev = x;
        timestamp_prev = timestamp;
        return x;
    }

So if you are lucky enough to have spent 0.3 seconds between the class construction and the first call to operator(), then y_prev is correctly initialized.

sylque avatar Sep 26 '24 14:09 sylque

You're right, in principle. The code has been this way for a long time. I think it works well in practice because the assumption is more or less that the motor starts at 0, so x would be 0. But in the case where the motor is moving when you start, or if you're applying the LPF to angle rather than velocity, it probably makes more sense to initialize it from x.

Another goal we have is to make the filter configurable, so you could swap it for a different kind of filter implementation. Maybe these issues can be solved at the same time by giving the user more control over the filter setup and initialisation.

runger1101001 avatar Sep 30 '24 10:09 runger1101001

Yes, I discovered this when investigating an issue with BLDCMotor::shaftAngle(): the result is wrong at startup because it uses the LPF with an angle which is never initially zero.

sylque avatar Sep 30 '24 10:09 sylque