Arduino-PID-Library
Arduino-PID-Library copied to clipboard
Allow to set resolution and to compute every time the function is called
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?
if you want to get consistent behavior from the PID, you cannot calculate every time the function is called
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
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 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.
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?