ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
pid_autotuner.cpp
Go to the documentation of this file.
1#include "pid_autotuner.h"
2#include "esphome/core/log.h"
3#include <cinttypes>
4#include <numbers>
5
6namespace esphome::pid {
7
8static const char *const TAG = "pid.autotune";
9
10/*
11 * # PID Autotuner
12 *
13 * Autotuning of PID parameters is a very interesting topic. There has been
14 * a lot of research over the years to create algorithms that can efficiently determine
15 * suitable starting PID parameters.
16 *
17 * The most basic approach is the Ziegler-Nichols method, which can determine good PID parameters
18 * in a manual process:
19 * - Set ki, kd to zero.
20 * - Increase kp until the output oscillates *around* the setpoint. This value kp is called the
21 * "ultimate gain" K_u.
22 * - Additionally, record the period of the observed oscillation as P_u (also called T_u).
23 * - suitable PID parameters are then: kp=0.6*K_u, ki=1.2*K_u/P_u, kd=0.075*K_u*P_u (additional variants of
24 * these "magic" factors exist as well [2]).
25 *
26 * Now we'd like to automate that process to get K_u and P_u without the user. So we'd like to somehow
27 * make the observed variable oscillate. One observation is that in many applications of PID controllers
28 * the observed variable has some amount of "delay" to the output value (think heating an object, it will
29 * take a few seconds before the sensor can sense the change of temperature) [3].
30 *
31 * It turns out one way to induce such an oscillation is by using a really dumb heating controller:
32 * When the observed value is below the setpoint, heat at 100%. If it's below, cool at 100% (or disable heating).
33 * We call this the "RelayFunction" - the class is responsible for making the observed value oscillate around the
34 * setpoint. We actually use a hysteresis filter (like the bang bang controller) to make the process immune to
35 * noise in the input data, but the math is the same [1].
36 *
37 * Next, now that we have induced an oscillation, we want to measure the frequency (or period) of oscillation.
38 * This is what "OscillationFrequencyDetector" is for: it records zerocrossing events (when the observed value
39 * crosses the setpoint). From that data, we can determine the average oscillating period. This is the P_u of the
40 * ZN-method.
41 *
42 * Finally, we need to determine K_u, the ultimate gain. It turns out we can calculate this based on the amplitude of
43 * oscillation ("induced amplitude `a`) as described in [1]:
44 * K_u = (4d) / (πa)
45 * where d is the magnitude of the relay function (in range -d to +d).
46 * To measure `a`, we look at the current phase the relay function is in - if it's in the "heating" phase, then we
47 * expect the lowest temperature (=highest error) to be found in the phase because the peak will always happen slightly
48 * after the relay function has changed state (assuming a delay-dominated process).
49 *
50 * Finally, we use some heuristics to determine if the data we've received so far is good:
51 * - First, of course we must have enough data to calculate the values.
52 * - The ZC events need to happen at a relatively periodic rate. If the heating/cooling speeds are very different,
53 * I've observed the ZN parameters are not very useful.
54 * - The induced amplitude should not deviate too much. If the amplitudes deviate too much this means there has
55 * been some outside influence (or noise) on the system, and the measured amplitude values are not reliable.
56 *
57 * There are many ways this method can be improved, but on my simulation data the current method already produces very
58 * good results. Some ideas for future improvements:
59 * - Relay Function improvements:
60 * - Integrator, Preload, Saturation Relay ([1])
61 * - Use phase of measured signal relative to relay function.
62 * - Apply PID parameters from ZN, but continuously tweak them in a second step.
63 *
64 * [1]: https://warwick.ac.uk/fac/cross_fac/iatl/reinvention/archive/volume5issue2/hornsey/
65 * [2]: http://www.mstarlabs.com/control/znrule.html
66 * [3]: https://www.academia.edu/38620114/SEBORG_3rd_Edition_Process_Dynamics_and_Control
67 */
68
69PIDAutotuner::PIDAutotuneResult PIDAutotuner::update(float setpoint, float process_variable) {
71 if (this->state_ == AUTOTUNE_SUCCEEDED) {
73 return res;
74 }
75
76 if (!std::isnan(this->setpoint_) && this->setpoint_ != setpoint) {
77 ESP_LOGW(TAG, "%s: Setpoint changed during autotune! The result will not be accurate!", this->id_.c_str());
78 }
79 this->setpoint_ = setpoint;
80
81 float error = setpoint - process_variable;
82 const uint32_t now = millis();
83
84 float output = this->relay_function_.update(error);
85 this->frequency_detector_.update(now, error);
87 res.output = output;
88
89 if (!this->frequency_detector_.has_enough_data() || !this->amplitude_detector_.has_enough_data()) {
90 // not enough data for calculation yet
91 ESP_LOGV(TAG, "%s: Not enough data yet for autotuner", this->id_.c_str());
92 return res;
93 }
94
95 bool zc_symmetrical = this->frequency_detector_.is_increase_decrease_symmetrical();
96 bool amplitude_convergent = this->amplitude_detector_.is_amplitude_convergent();
97 if (!zc_symmetrical || !amplitude_convergent) {
98 // The frequency/amplitude is not fully accurate yet, try to wait
99 // until the fault clears, or terminate after a while anyway
100 if (!zc_symmetrical) {
101 ESP_LOGVV(TAG, "%s: ZC is not symmetrical", this->id_.c_str());
102 }
103 if (!amplitude_convergent) {
104 ESP_LOGVV(TAG, "%s: Amplitude is not convergent", this->id_.c_str());
105 }
107 ESP_LOGVV(TAG, "%s: >", this->id_.c_str());
108 ESP_LOGVV(TAG, " Phase %" PRIu32 ", enough=%" PRIu32, phase, enough_data_phase_);
109
110 if (this->enough_data_phase_ == 0) {
111 this->enough_data_phase_ = phase;
112 } else if (phase - this->enough_data_phase_ <= 6) {
113 // keep trying for at least 6 more phases
114 return res;
115 } else {
116 // proceed to calculating PID parameters
117 // warning will be shown in "Checks" section
118 }
119 }
120
121 ESP_LOGI(TAG, "%s: PID Autotune finished!", this->id_.c_str());
122
124 float d = (this->relay_function_.output_positive - this->relay_function_.output_negative) / 2.0f;
125 ESP_LOGVV(TAG, " Relay magnitude: %f", d);
126 this->ku_ = 4.0f * d / (std::numbers::pi_v<float> * osc_ampl);
128
131 this->dump_config();
132
133 return res;
134}
136 if (this->state_ == AUTOTUNE_SUCCEEDED) {
137 ESP_LOGI(TAG,
138 "%s: PID Autotune:\n"
139 " State: Succeeded!",
140 this->id_.c_str());
141 bool has_issue = false;
143 ESP_LOGW(TAG, " Could not reliably determine oscillation amplitude, PID parameters may be inaccurate!\n"
144 " Please make sure you eliminate all outside influences on the measured temperature.");
145 has_issue = true;
146 }
148 ESP_LOGW(TAG,
149 " Oscillation Frequency is not symmetrical. PID parameters may be inaccurate!\n"
150 " This is usually because the heat and cool processes do not change the temperature at the same "
151 "rate.\n"
152 " Please try reducing the positive_output value (or increase negative_output in case of a cooler)");
153 has_issue = true;
154 }
155 if (!has_issue) {
156 ESP_LOGI(TAG, " All checks passed!");
157 }
158
159 auto fac = get_ziegler_nichols_pid_();
160 ESP_LOGI(TAG,
161 " Calculated PID parameters (\"Ziegler-Nichols PID\" rule):\n"
162 "\n"
163 " control_parameters:\n"
164 " kp: %.5f\n"
165 " ki: %.5f\n"
166 " kd: %.5f\n"
167 "\n"
168 " Please copy these values into your YAML configuration! They will reset on the next reboot.",
169 fac.kp, fac.ki, fac.kd);
170
171 ESP_LOGV(TAG,
172 " Oscillation Period: %f\n"
173 " Oscillation Amplitude: %f\n"
174 " Ku: %f, Pu: %f",
176 this->amplitude_detector_.get_mean_oscillation_amplitude(), this->ku_, this->pu_);
177
178 ESP_LOGD(TAG, " Alternative Rules:");
179 // http://www.mstarlabs.com/control/znrule.html
180 print_rule_("Ziegler-Nichols PI", 0.45f, 0.54f, 0.0f);
181 print_rule_("Pessen Integral PID", 0.7f, 1.75f, 0.105f);
182 print_rule_("Some Overshoot PID", 0.333f, 0.667f, 0.111f);
183 print_rule_("No Overshoot PID", 0.2f, 0.4f, 0.0625f);
184 ESP_LOGI(TAG, "%s: Autotune completed", this->id_.c_str());
185 }
186
187 if (this->state_ == AUTOTUNE_RUNNING) {
188 ESP_LOGD(TAG,
189 "%s: PID Autotune:\n"
190 " Autotune is still running!\n"
191 " Status: Trying to reach %.2f °C\n"
192 " Stats so far:\n"
193 " Phases: %" PRIu32 "\n"
194 " Detected %zu zero-crossings\n"
195 " Current Phase Min: %.2f, Max: %.2f",
199 }
200}
201PIDAutotuner::PIDResult PIDAutotuner::calculate_pid_(float kp_factor, float ki_factor, float kd_factor) {
202 float kp = kp_factor * ku_;
203 float ki = ki_factor * ku_ / pu_;
204 float kd = kd_factor * ku_ * pu_;
205 return {
206 .kp = kp,
207 .ki = ki,
208 .kd = kd,
209 };
210}
211void PIDAutotuner::print_rule_(const char *name, float kp_factor, float ki_factor, float kd_factor) {
212 auto fac = calculate_pid_(kp_factor, ki_factor, kd_factor);
213 ESP_LOGD(TAG,
214 " Rule '%s':\n"
215 " kp: %.5f, ki: %.5f, kd: %.5f",
216 name, fac.kp, fac.ki, fac.kd);
217}
218
219// ================== RelayFunction ==================
221 if (this->state == RELAY_FUNCTION_INIT) {
222 bool pos = error > this->noiseband;
224 }
225 bool change = false;
226 if (this->state == RELAY_FUNCTION_POSITIVE && error < -this->noiseband) {
227 // Positive hysteresis reached, change direction
229 change = true;
230 } else if (this->state == RELAY_FUNCTION_NEGATIVE && error > this->noiseband) {
231 // Negative hysteresis reached, change direction
233 change = true;
234 }
235
237 if (change) {
238 this->phase_count++;
239 }
240
241 return output;
242}
243
244// ================== OscillationFrequencyDetector ==================
246 if (this->state == FREQUENCY_DETECTOR_INIT) {
247 bool pos = error > this->noiseband;
248 state = pos ? FREQUENCY_DETECTOR_POSITIVE : FREQUENCY_DETECTOR_NEGATIVE;
249 }
250
251 bool had_crossing = false;
252 if (this->state == FREQUENCY_DETECTOR_POSITIVE && error < -this->noiseband) {
253 this->state = FREQUENCY_DETECTOR_NEGATIVE;
254 had_crossing = true;
255 } else if (this->state == FREQUENCY_DETECTOR_NEGATIVE && error > this->noiseband) {
256 this->state = FREQUENCY_DETECTOR_POSITIVE;
257 had_crossing = true;
258 }
259
260 if (had_crossing) {
261 // Had crossing above hysteresis threshold, record
262 if (this->last_zerocross != 0) {
263 uint32_t dt = now - this->last_zerocross;
264 this->zerocrossing_intervals.push_back(dt);
265 }
266 this->last_zerocross = now;
267 }
268}
270 // Do we have enough data in this detector to generate PID values?
271 return this->zerocrossing_intervals.size() >= 2;
272}
274 // Get the mean oscillation period in seconds
275 // Only call if has_enough_data() has returned true.
276 float sum = 0.0f;
277 for (uint32_t v : this->zerocrossing_intervals)
278 sum += v;
279 // zerocrossings are each half-period, multiply by 2
280 float mean_value = sum / this->zerocrossing_intervals.size();
281 // divide by 1000 to get seconds, multiply by two because zc happens two times per period
282 float mean_period = mean_value / 1000 * 2;
283 return mean_period;
284}
286 // Check if increase/decrease of process value was symmetrical
287 // If the process value increases much faster than it decreases, the generated PID values will
288 // not be very good and the function output values need to be adjusted
289 // Happens for example with a well-insulated heating element.
290 // We calculate this based on the zerocrossing interval.
291 if (zerocrossing_intervals.empty())
292 return false;
293 uint32_t max_interval = zerocrossing_intervals[0];
294 uint32_t min_interval = zerocrossing_intervals[0];
295 for (uint32_t interval : zerocrossing_intervals) {
296 max_interval = std::max(max_interval, interval);
297 min_interval = std::min(min_interval, interval);
298 }
299 float ratio = min_interval / float(max_interval);
300 return ratio >= 0.66f;
301}
302
303// ================== OscillationAmplitudeDetector ==================
306 if (relay_state != last_relay_state) {
307 if (last_relay_state == RelayFunction::RELAY_FUNCTION_POSITIVE) {
308 // Transitioned from positive error to negative error.
309 // The positive error peak must have been in previous segment (180° shifted)
310 // record phase_max
311 this->phase_maxs.push_back(phase_max);
312 } else if (last_relay_state == RelayFunction::RELAY_FUNCTION_NEGATIVE) {
313 // Transitioned from negative error to positive error.
314 // The negative error peak must have been in previous segment (180° shifted)
315 // record phase_min
316 this->phase_mins.push_back(phase_min);
317 }
318 // reset phase values for next phase
319 this->phase_min = error;
320 this->phase_max = error;
321 }
322 this->last_relay_state = relay_state;
323
324 this->phase_min = std::min(this->phase_min, error);
325 this->phase_max = std::max(this->phase_max, error);
326
327 // Check arrays sizes, we keep at most 7 items (6 datapoints is enough, and data at beginning might not
328 // have been stabilized)
329 if (this->phase_maxs.size() > 7)
330 this->phase_maxs.erase(this->phase_maxs.begin());
331 if (this->phase_mins.size() > 7)
332 this->phase_mins.erase(this->phase_mins.begin());
333}
335 // Return if we have enough data to generate PID parameters
336 // The first phase is not very useful if the setpoint is not set to the starting process value
337 // So discard first phase. Otherwise we need at least two phases.
338 return std::min(phase_mins.size(), phase_maxs.size()) >= 3;
339}
341 float total_amplitudes = 0;
342 size_t total_amplitudes_n = 0;
343 for (size_t i = 1; i < std::min(phase_mins.size(), phase_maxs.size()) - 1; i++) {
344 total_amplitudes += std::abs(phase_maxs[i] - phase_mins[i + 1]);
345 total_amplitudes_n++;
346 }
347 float mean_amplitude = total_amplitudes / total_amplitudes_n;
348 // Amplitude is measured from center, divide by 2
349 return mean_amplitude / 2.0f;
350}
352 // Check if oscillation amplitude is convergent
353 // We implement this by checking global extrema against average amplitude
354 if (this->phase_mins.empty() || this->phase_maxs.empty())
355 return false;
356
357 float global_max = phase_maxs[0], global_min = phase_mins[0];
358 for (auto v : this->phase_mins)
359 global_min = std::min(global_min, v);
360 for (auto v : this->phase_maxs)
361 global_max = std::max(global_max, v);
362 float global_amplitude = (global_max - global_min) / 2.0f;
363 float mean_amplitude = this->get_mean_oscillation_amplitude();
364 return (mean_amplitude - global_amplitude) / (global_amplitude) < 0.05f;
365}
366
367} // namespace esphome::pid
PIDAutotuneResult update(float setpoint, float process_variable)
struct esphome::pid::PIDAutotuner::OscillationAmplitudeDetector amplitude_detector_
enum esphome::pid::PIDAutotuner::State state_
struct esphome::pid::PIDAutotuner::RelayFunction relay_function_
PIDResult calculate_pid_(float kp_factor, float ki_factor, float kd_factor)
void print_rule_(const char *name, float kp_factor, float ki_factor, float kd_factor)
PIDResult get_ziegler_nichols_pid_()
struct esphome::pid::PIDAutotuner::OscillationFrequencyDetector frequency_detector_
bool state
Definition fan.h:2
size_t size_t pos
Definition helpers.h:1052
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t
void update(float error, RelayFunction::RelayFunctionState relay_state)
enum esphome::pid::PIDAutotuner::RelayFunction::RelayFunctionState state