Arduino-PID-Library icon indicating copy to clipboard operation
Arduino-PID-Library copied to clipboard

Implementation problems

Open vagran opened this issue 11 years ago • 5 comments

Sorry, not fork but just quick comment.

In Calculate method: ITerm+= (ki * error); Integration precision can be improved easily by using previous error value and integrate as trapezoid: prevError = *mySetpoint - lastInput; ITerm+= (ki * (error + prevError) / 2.0);

Second, you calculate derivative of input instead of derivative of error value as it should be done in canonical PID-regulator. < dInput = (input - lastInput);

dError = (errror - prevError);

< double output = kp * error + ITerm- kd * dInput;

double output = kp * error + ITerm + kd * dError;

vagran avatar Oct 07 '14 09:10 vagran

There are even better integration-algorithms available, but they all cost cycles. I like the idea changing to the trapezoid-method. maybe we should make it optional with a compilerswitch?

orgua avatar Apr 29 '15 06:04 orgua

Your committed implementation could be even simpler because you don't use the new variable more than once and can safe the 4byte ram:
ITerm+= (ki * (error + *mySetpoint - lastInput) / 2.0); // trapezoid

orgua avatar Apr 29 '15 07:04 orgua

Your committed implementation could be even simpler because you don't use the new variable more than once and can safe the 4byte ram

I think, the compiler is smart enough to not allocate RAM for temporal variables. I can bet that the compiled code will be the same in both cases. One should prefer readability over micro-optimizations, the compiler will do the all the dirty work.

vagran avatar Apr 29 '15 07:04 vagran

What about the second point? The commit does not touch the derivative.

vagran avatar Apr 29 '15 07:04 vagran

You are right when you want to maintain the readability and allocate a local variable: double lastError = *mySetpoint - lastInput; ITerm+= (ki * (error + lastError) / 2.0); This code compiles the same as my last given codeline. That are 30 instructions and 4 byte of ram less (in the PID-basic-example), than with your semi-global class-variable.

And for your second point: do the math. everything is ok, it's the same. he took a shortcut, expanded the "output"-formular and optimized the calculation

orgua avatar Apr 29 '15 07:04 orgua