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

Allow to set resolution and to compute every time the function is called

Open Lauszus opened this issue 11 years ago • 5 comments

First of all. Thanks for a great library. I just started to use it for my balancing robot: https://github.com/TKJElectronics/Balanduino/tree/dev/Firmware/Balanduino, but I wanted to change it a bit for my needs.

This is the changes I have done:

  • I added the function SetResolution, this will allow the user to set the resolution to either milliseconds or microseconds.
  • By calling SetSampleTime with 0. Compute will calculate the angle every time it is called. This is needed for my robot as I want to update the PID loop as fast as possible.

Also do you mind if I fix the indent of the source code?

Lauszus avatar Jul 19 '13 15:07 Lauszus

if you want to get consistent behavior from the PID, you cannot calculate every time the function is called

see Improving the Beginner’s PID – Sample Time

enjoyneering avatar Jan 11 '19 14:01 enjoyneering

Not sure if this is the issue lauszus is trying to solve, but I had a similar one with my balancing robot. The robot needs to sample an imu and run the pid every 10ms. The main loop is already setup to run at that rate. If you let the pid decide when to run using its internal timer it will get out of sync with the main loop and not always run. So I changed the pid to run every time it is called, set time interval to 10ms and let the main loop sample the imu and run the pid every 10 ms

MiloMindbender avatar Jan 12 '19 16:01 MiloMindbender

did you try set time smaller than 10ms? setSampleTime(9);

In this case, the PID is synchronized. unsigned long timeChange = (now - lastTime); if(timeChange>=SampleTime) ......

enjoyneering avatar Jan 14 '19 16:01 enjoyneering

@enjoyneering actually that doesn't work, the loop will execute every 10ms so the PID will always run, but the time constants INSIDE the PID will be set to 9ms so the calculations will be off.

MiloMindbender avatar Jan 14 '19 21:01 MiloMindbender

I agree it will be off, because the sample time is hard-coded to Ki & Kd gains

kp = Kp; ki = Ki * SampleTimeInSec; kd = Kd / SampleTimeInSec;

so in your case you still have to set up sample time to 10

setSampleTime(10);

and then bypass sample time check in the "compute()" function. Am I right?

enjoyneering avatar Jan 16 '19 14:01 enjoyneering