From 1c94875c10732222e5d64c1e30ce7aeb5b5e3e44 Mon Sep 17 00:00:00 2001 From: saullipton Date: Fri, 9 Nov 2018 16:46:28 -0600 Subject: [PATCH] Faster AutoPID Changed millis() to micros() to allow the function to run as fast as one can get it to - e.g. on a Due. For PID loops, the essential performance element is the speed at which the loop can be closed. It makes little sense to limit this to 1ms. Millis() will cycle over after 70 minutes, however the code looks like it will only skip one PID execution at that time. --- AutoPID.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/AutoPID.cpp b/AutoPID.cpp index 64a5f49..6b61c8a 100644 --- a/AutoPID.cpp +++ b/AutoPID.cpp @@ -48,14 +48,14 @@ void AutoPID::run() { //if bang thresholds are defined and we're outside of them, use bang-bang control if (_bangOn && ((*_setpoint - *_input) > _bangOn)) { *_output = _outputMax; - _lastStep = millis(); + _lastStep = micros(); } else if (_bangOff && ((*_input - *_setpoint) > _bangOff)) { *_output = _outputMin; - _lastStep = millis(); + _lastStep = micros(); } else { //otherwise use PID control - unsigned long _dT = millis() - _lastStep; //calculate time since last update + unsigned long _dT = micros() - _lastStep; //calculate time since last update if (_dT >= _timeStep) { //if long enough, do PID calculations - _lastStep = millis(); + _lastStep = micros(); double _error = *_setpoint - *_input; _integral += (_error + _previousError) / 2 * _dT / 1000.0; //Riemann sum integral //_integral = constrain(_integral, _outputMin/_Ki, _outputMax/_Ki); @@ -73,7 +73,7 @@ void AutoPID::stop() { reset(); } void AutoPID::reset() { - _lastStep = millis(); + _lastStep = micros(); _integral = 0; _previousError = 0; } @@ -92,8 +92,8 @@ void AutoPID::setIntegral(double integral){ void AutoPIDRelay::run() { AutoPID::run(); - while ((millis() - _lastPulseTime) > _pulseWidth) _lastPulseTime += _pulseWidth; - *_relayState = ((millis() - _lastPulseTime) < (_pulseValue * _pulseWidth)); + while ((micros() - _lastPulseTime) > _pulseWidth) _lastPulseTime += _pulseWidth; + *_relayState = ((micros() - _lastPulseTime) < (_pulseValue * _pulseWidth)); } @@ -101,4 +101,3 @@ double AutoPIDRelay::getPulseValue(){ return (isStopped()?0:_pulseValue); } -