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