Add 1 bit to temo runaway making max setting > 60 minutes
[clinton/Smoothieware.git] / src / modules / tools / temperaturecontrol / TemperatureControl.cpp
CommitLineData
df27a6a3 1/*
cd011f58
AW
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
df27a6a3 5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
cd011f58
AW
6*/
7
7b49793d 8// TODO : THIS FILE IS LAME, MUST BE MADE MUCH BETTER
cd011f58 9
ded56b35
AW
10#include "libs/Module.h"
11#include "libs/Kernel.h"
12#include <math.h>
13#include "TemperatureControl.h"
3c308aeb 14#include "TemperatureControlPool.h"
3c132bd0 15#include "libs/Pin.h"
3c4f2dd8 16#include "modules/robot/Conveyor.h"
8293d443 17#include "PublicDataRequest.h"
2fa50ca0 18
38b9f24a
L
19#include "PublicData.h"
20#include "ToolManagerPublicAccess.h"
61134a65
JM
21#include "StreamOutputPool.h"
22#include "Config.h"
23#include "checksumm.h"
24#include "Gcode.h"
61134a65 25#include "SlowTicker.h"
8d54c34c 26#include "ConfigValue.h"
66383b80 27#include "PID_Autotuner.h"
1f8dab1a
JM
28#include "SerialMessage.h"
29#include "utils.h"
ded56b35 30
9d955060 31// Temp sensor implementations:
32#include "Thermistor.h"
4710532a 33#include "max31855.h"
073d88ec 34#include "AD8495.h"
9d955060 35
8f91e4e6
MM
36#include "MRI_Hooks.h"
37
85eabc50
JM
38#define UNDEFINED -1
39
9d955060 40#define sensor_checksum CHECKSUM("sensor")
41
85eabc50
JM
42#define readings_per_second_checksum CHECKSUM("readings_per_second")
43#define max_pwm_checksum CHECKSUM("max_pwm")
44#define pwm_frequency_checksum CHECKSUM("pwm_frequency")
989d0e94
JM
45#define bang_bang_checksum CHECKSUM("bang_bang")
46#define hysteresis_checksum CHECKSUM("hysteresis")
85eabc50 47#define heater_pin_checksum CHECKSUM("heater_pin")
bb02929e 48#define max_temp_checksum CHECKSUM("max_temp")
3a014cbb 49#define min_temp_checksum CHECKSUM("min_temp")
85eabc50
JM
50
51#define get_m_code_checksum CHECKSUM("get_m_code")
52#define set_m_code_checksum CHECKSUM("set_m_code")
53#define set_and_wait_m_code_checksum CHECKSUM("set_and_wait_m_code")
54
55#define designator_checksum CHECKSUM("designator")
56
57#define p_factor_checksum CHECKSUM("p_factor")
58#define i_factor_checksum CHECKSUM("i_factor")
59#define d_factor_checksum CHECKSUM("d_factor")
60
61#define i_max_checksum CHECKSUM("i_max")
08f89868 62#define windup_checksum CHECKSUM("windup")
85eabc50
JM
63
64#define preset1_checksum CHECKSUM("preset1")
65#define preset2_checksum CHECKSUM("preset2")
66
1cd1bf1a 67#define runaway_range_checksum CHECKSUM("runaway_range")
1cd1bf1a 68#define runaway_heating_timeout_checksum CHECKSUM("runaway_heating_timeout")
4f97f8b8 69#define runaway_cooling_timeout_checksum CHECKSUM("runaway_cooling_timeout")
1cd1bf1a 70
8e8b938e 71TemperatureControl::TemperatureControl(uint16_t name, int index)
d8baddd9 72{
8e8b938e
JM
73 name_checksum= name;
74 pool_index= index;
75 waiting= false;
01004e36 76 temp_violated= false;
8e8b938e 77 sensor= nullptr;
71cc73eb 78 readonly= false;
4f97f8b8 79 tick= 0;
d8baddd9 80}
ded56b35 81
d8baddd9 82TemperatureControl::~TemperatureControl()
83{
84 delete sensor;
85}
4710532a
JM
86
87void TemperatureControl::on_module_loaded()
88{
907d5e8a 89
81b547a1 90 // We start not desiring any temp
907d5e8a 91 this->target_temperature = UNDEFINED;
f1e38d95 92 this->sensor_settings= false; // set to true if sensor settings have been overriden
ded56b35
AW
93
94 // Settings
71cc73eb 95 this->load_config();
ded56b35 96
ded56b35 97 // Register for events
b0be67b5 98 this->register_for_event(ON_GCODE_RECEIVED);
8293d443 99 this->register_for_event(ON_GET_PUBLIC_DATA);
71cc73eb
JM
100
101 if(!this->readonly) {
71cc73eb
JM
102 this->register_for_event(ON_SECOND_TICK);
103 this->register_for_event(ON_MAIN_LOOP);
104 this->register_for_event(ON_SET_PUBLIC_DATA);
105 this->register_for_event(ON_HALT);
106 }
3d1a4519
JM
107}
108
109void TemperatureControl::on_halt(void *arg)
110{
728477c4
JM
111 if(arg == nullptr) {
112 // turn off heater
113 this->o = 0;
114 this->heater_pin.set(0);
115 this->target_temperature = UNDEFINED;
116 }
ded56b35
AW
117}
118
4710532a
JM
119void TemperatureControl::on_main_loop(void *argument)
120{
01004e36
JM
121 if (this->temp_violated) {
122 this->temp_violated = false;
f46f7916 123 THEKERNEL->streams->printf("ERROR: MINTEMP or MAXTEMP triggered on %s. Check your temperature sensors!\n", designator.c_str());
01004e36
JM
124 THEKERNEL->streams->printf("HALT asserted - reset or M999 required\n");
125 THEKERNEL->call_event(ON_HALT, nullptr);
a7f12bed 126 }
7e57bc2c 127}
7dd8133c
AW
128
129// Get configuration from the config file
71cc73eb 130void TemperatureControl::load_config()
4710532a 131{
7dd8133c 132
1306ba99 133 // General config
314ab8f7
MM
134 this->set_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_m_code_checksum)->by_default(104)->as_number();
135 this->set_and_wait_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_and_wait_m_code_checksum)->by_default(109)->as_number();
136 this->get_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, get_m_code_checksum)->by_default(105)->as_number();
137 this->readings_per_second = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, readings_per_second_checksum)->by_default(20)->as_number();
7dee00e4 138
314ab8f7 139 this->designator = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, designator_checksum)->by_default(string("T"))->as_string();
b0be67b5 140
1cd1bf1a 141 // Runaway parameters
6c8b8ca0 142 uint32_t n= THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, runaway_range_checksum)->by_default(20)->as_number();
5cc0bc2c
JM
143 if(n > 63) n= 63;
144 this->runaway_range= n;
4f97f8b8 145
8123c72d 146 // these need to fit in 9 bits after dividing by 8 so max is 4088 secs or 68 minutes
6c8b8ca0 147 n= THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, runaway_heating_timeout_checksum)->by_default(900)->as_number();
8123c72d 148 if(n > 4088) n= 4088;
4f97f8b8
JM
149 this->runaway_heating_timeout = n/8; // we have 8 second ticks
150 n= THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, runaway_cooling_timeout_checksum)->by_default((float)n)->as_number();
8123c72d 151 if(n > 4088) n= 4088;
4f97f8b8 152 this->runaway_cooling_timeout = n/8;
1cd1bf1a 153
3a014cbb 154 // Max and min temperatures we are not allowed to get over (Safety)
01004e36 155 this->max_temp = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_temp_checksum)->by_default(300)->as_number();
3a014cbb 156 this->min_temp = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, min_temp_checksum)->by_default(0)->as_number();
7d4baeee 157
71cc73eb
JM
158 // Heater pin
159 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->by_default("nc")->as_string());
160 if(this->heater_pin.connected()){
161 this->readonly= false;
162 this->heater_pin.as_output();
163
164 } else {
165 this->readonly= true;
166 }
167
d8baddd9 168 // For backward compatibility, default to a thermistor sensor.
169 std::string sensor_type = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, sensor_checksum)->by_default("thermistor")->as_string();
170
171 // Instantiate correct sensor (TBD: TempSensor factory?)
172 delete sensor;
173 sensor = nullptr; // In case we fail to create a new sensor.
4710532a 174 if(sensor_type.compare("thermistor") == 0) {
d8baddd9 175 sensor = new Thermistor();
4710532a 176 } else if(sensor_type.compare("max31855") == 0) {
d8baddd9 177 sensor = new Max31855();
073d88ec
E
178 } else if(sensor_type.compare("ad8495") == 0) {
179 sensor = new AD8495();
4710532a 180 } else {
d8baddd9 181 sensor = new TempSensor(); // A dummy implementation
182 }
183 sensor->UpdateConfig(temperature_control_checksum, this->name_checksum);
4710532a 184
71cc73eb
JM
185 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
186 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
f4bd4fc3 187
907d5e8a 188
c4f4cf73 189 // sigma-delta output modulation
b35ac71e 190 this->o = 0;
3c132bd0 191
71cc73eb
JM
192 if(!this->readonly) {
193 // used to enable bang bang control of heater
194 this->use_bangbang = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
195 this->hysteresis = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
08f89868 196 this->windup = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, windup_checksum)->by_default(false)->as_bool();
71cc73eb
JM
197 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
198 this->heater_pin.set(0);
199 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
200 // activate SD-DAC timer
201 THEKERNEL->slow_ticker->attach( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, pwm_frequency_checksum)->by_default(2000)->as_number(), &heater_pin, &Pwm::on_tick);
202 }
8f91e4e6 203
907d5e8a 204
f39da6fe 205 // reading tick
314ab8f7 206 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
4710532a 207 this->PIDdt = 1.0 / this->readings_per_second;
f39da6fe 208
907d5e8a 209 // PID
314ab8f7 210 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
1ad23cd3 211 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
314ab8f7 212 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
71cc73eb
JM
213
214 if(!this->readonly) {
215 // set to the same as max_pwm by default
216 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
217 }
218
10e66797 219 this->iTerm = 0.0;
4710532a 220 this->lastInput = -1.0;
907d5e8a 221 this->last_reading = 0.0;
7dd8133c
AW
222}
223
4710532a
JM
224void TemperatureControl::on_gcode_received(void *argument)
225{
226 Gcode *gcode = static_cast<Gcode *>(argument);
8dfbc976 227 if (gcode->has_m) {
ee4711d1 228
4710532a 229 if( gcode->m == this->get_m_code ) {
93284f6f 230 char buf[32]; // should be big enough for any status
3517edce 231 int n = snprintf(buf, sizeof(buf), "%s:%3.1f /%3.1f @%d ", this->designator.c_str(), this->get_temperature(), ((target_temperature <= 0) ? 0.0 : target_temperature), this->o);
93284f6f 232 gcode->txt_after_ok.append(buf, n);
71cc73eb
JM
233 return;
234 }
8dfbc976 235
76f53dc6 236 if (gcode->m == 305) { // set or get sensor settings
76f53dc6 237 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
1f8dab1a 238 TempSensor::sensor_options_t args= gcode->get_args();
d22755f7
JM
239 args.erase('S'); // don't include the S
240 if(args.size() > 0) {
76f53dc6 241 // set the new options
d22755f7
JM
242 if(sensor->set_optional(args)) {
243 this->sensor_settings= true;
244 }else{
245 gcode->stream->printf("Unable to properly set sensor settings, make sure you specify all required values\n");
246 }
247 }else{
248 // don't override
249 this->sensor_settings= false;
76f53dc6
JM
250 }
251
252 }else if(!gcode->has_letter('S')) {
d22755f7 253 gcode->stream->printf("%s(S%d): using %s\n", this->designator.c_str(), this->pool_index, this->readonly?"Readonly" : this->use_bangbang?"Bangbang":"PID");
76f53dc6
JM
254 sensor->get_raw();
255 TempSensor::sensor_options_t options;
256 if(sensor->get_optional(options)) {
257 for(auto &i : options) {
258 // foreach optional value
a2e5f877 259 gcode->stream->printf("%s(S%d): %c %1.18f\n", this->designator.c_str(), this->pool_index, i.first, i.second);
76f53dc6
JM
260 }
261 }
262 }
263
264 return;
265 }
266
71cc73eb
JM
267 // readonly sensors don't handle the rest
268 if(this->readonly) return;
269
01004e36
JM
270 if (gcode->m == 143) {
271 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
272 if(gcode->has_letter('P')) {
273 max_temp= gcode->get_value('P');
274
275 } else {
276 gcode->stream->printf("Nothing set NOTE Usage is M143 S0 P300 where <S> is the hotend index and <P> is the maximum temp to set\n");
277 }
278
279 }else if(gcode->get_num_args() == 0) {
280 gcode->stream->printf("Maximum temperature for %s(%d) is %f°C\n", this->designator.c_str(), this->pool_index, max_temp);
281 }
282
283 } else if (gcode->m == 301) {
4710532a 284 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
827a49ca 285 if (gcode->has_letter('P'))
201e6dcf 286 setPIDp( gcode->get_value('P') );
827a49ca 287 if (gcode->has_letter('I'))
201e6dcf 288 setPIDi( gcode->get_value('I') );
827a49ca 289 if (gcode->has_letter('D'))
201e6dcf 290 setPIDd( gcode->get_value('D') );
827a49ca 291 if (gcode->has_letter('X'))
f1e38d95
JM
292 this->i_max = gcode->get_value('X');
293 if (gcode->has_letter('Y'))
294 this->heater_pin.max_pwm(gcode->get_value('Y'));
295
296 }else if(!gcode->has_letter('S')) {
297 gcode->stream->printf("%s(S%d): Pf:%g If:%g Df:%g X(I_max):%g max pwm: %d O:%d\n", this->designator.c_str(), this->pool_index, this->p_factor, this->i_factor / this->PIDdt, this->d_factor * this->PIDdt, this->i_max, this->heater_pin.max_pwm(), o);
298 }
299
4710532a 300 } else if (gcode->m == 500 || gcode->m == 503) { // M500 saves some volatile settings to config override file, M503 just prints the settings
f1e38d95
JM
301 gcode->stream->printf(";PID settings:\nM301 S%d P%1.4f I%1.4f D%1.4f X%1.4f Y%d\n", this->pool_index, this->p_factor, this->i_factor / this->PIDdt, this->d_factor * this->PIDdt, this->i_max, this->heater_pin.max_pwm());
302
01004e36
JM
303 gcode->stream->printf(";Max temperature setting:\nM143 S%d P%1.4f\n", this->pool_index, this->max_temp);
304
f1e38d95
JM
305 if(this->sensor_settings) {
306 // get or save any sensor specific optional values
307 TempSensor::sensor_options_t options;
308 if(sensor->get_optional(options) && !options.empty()) {
309 gcode->stream->printf(";Optional temp sensor specific settings:\nM305 S%d", this->pool_index);
310 for(auto &i : options) {
7d678d16 311 gcode->stream->printf(" %c%1.18f", i.first, i.second);
f1e38d95
JM
312 }
313 gcode->stream->printf("\n");
314 }
315 }
33e4cc02 316
8e8b938e 317 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S')) {
42cb1b30 318 // this only gets handled if it is not controlled by the tool manager or is active in the toolmanager
8e8b938e
JM
319 this->active = true;
320
321 // this is safe as old configs as well as single extruder configs the toolmanager will not be running so will return false
322 // this will also ignore anything that the tool manager is not controlling and return false, otherwise it returns the active tool
323 void *returned_data;
75e6428d 324 bool ok = PublicData::get_value( tool_manager_checksum, is_active_tool_checksum, this->name_checksum, &returned_data );
8e8b938e
JM
325 if (ok) {
326 uint16_t active_tool_name = *static_cast<uint16_t *>(returned_data);
327 this->active = (active_tool_name == this->name_checksum);
328 }
329
330 if(this->active) {
42cb1b30 331 // required so temp change happens in order
04782655 332 THEKERNEL->conveyor->wait_for_idle();
2134bcf2 333
42cb1b30 334 float v = gcode->get_value('S');
db453125 335
42cb1b30
JM
336 if (v == 0.0) {
337 this->target_temperature = UNDEFINED;
338 this->heater_pin.set((this->o = 0));
339 } else {
340 this->set_desired_temperature(v);
ed52bf31
JM
341 // wait for temp to be reached, no more gcodes will be fetched until this is complete
342 if( gcode->m == this->set_and_wait_m_code) {
487976f7 343 if(isinf(get_temperature()) && isinf(sensor->get_temperature())) {
f0433db4 344 THEKERNEL->streams->printf("Temperature reading is unreliable on %s HALT asserted - reset or M999 required\n", designator.c_str());
487976f7
JM
345 THEKERNEL->call_event(ON_HALT, nullptr);
346 return;
347 }
348
ed52bf31
JM
349 this->waiting = true; // on_second_tick will announce temps
350 while ( get_temperature() < target_temperature ) {
351 THEKERNEL->call_event(ON_IDLE, this);
798295c1 352 // check if ON_HALT was called (usually by kill button)
aa896868
JM
353 if(THEKERNEL->is_halted() || this->target_temperature == UNDEFINED) {
354 THEKERNEL->streams->printf("Wait on temperature aborted by kill\n");
355 break;
356 }
ed52bf31
JM
357 }
358 this->waiting = false;
42cb1b30 359 }
cf1a7632 360 }
907d5e8a 361 }
df27a6a3 362 }
df27a6a3 363 }
ded56b35
AW
364}
365
4710532a
JM
366void TemperatureControl::on_get_public_data(void *argument)
367{
368 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
201e6dcf 369
b19aa09d
JM
370 if(!pdr->starts_with(temperature_control_checksum)) return;
371
8e8b938e
JM
372 if(pdr->second_element_is(pool_index_checksum)) {
373 // asking for our instance pointer if we have this pool_index
374 if(pdr->third_element_is(this->pool_index)) {
375 static void *return_data;
376 return_data = this;
377 pdr->set_data_ptr(&return_data);
378 pdr->set_taken();
379 }
8e8b938e 380
56a6c8c1 381 }else if(pdr->second_element_is(poll_controls_checksum)) {
bab4e1bd 382 // polling for all temperature controls
3bfb2639
JM
383 // add our data to the list which is passed in via the data_ptr
384
385 std::vector<struct pad_temperature> *v= static_cast<std::vector<pad_temperature>*>(pdr->get_data_ptr());
bab4e1bd 386
3bfb2639 387 struct pad_temperature t;
bab4e1bd 388 // setup data
3bfb2639
JM
389 t.current_temperature = this->get_temperature();
390 t.target_temperature = (target_temperature <= 0) ? 0 : this->target_temperature;
391 t.pwm = this->o;
392 t.designator= this->designator;
393 t.id= this->name_checksum;
394 v->push_back(t);
395 pdr->set_taken();
b19aa09d 396
56a6c8c1
JM
397 }else if(pdr->second_element_is(current_temperature_checksum)) {
398 // if targeted at us
399 if(pdr->third_element_is(this->name_checksum)) {
564cf1f0 400 // ok this is targeted at us, so set the requ3sted data in the pointer passed into us
56a6c8c1
JM
401 struct pad_temperature *t= static_cast<pad_temperature*>(pdr->get_data_ptr());
402 t->current_temperature = this->get_temperature();
403 t->target_temperature = (target_temperature <= 0) ? 0 : this->target_temperature;
404 t->pwm = this->o;
405 t->designator= this->designator;
406 t->id= this->name_checksum;
407 pdr->set_taken();
56a6c8c1 408 }
b19aa09d 409 }
8e8b938e 410
8293d443 411}
db453125 412
4710532a
JM
413void TemperatureControl::on_set_public_data(void *argument)
414{
415 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
77047e76 416
991d98cc 417 if(!pdr->starts_with(temperature_control_checksum)) return;
77047e76 418
8e8b938e 419 if(!pdr->second_element_is(this->name_checksum)) return;
77047e76 420
991d98cc 421 // ok this is targeted at us, so set the temp
ed52bf31 422 // NOTE unlike the M code this will set the temp now not when the queue is empty
4710532a 423 float t = *static_cast<float *>(pdr->get_data_ptr());
991d98cc
JM
424 this->set_desired_temperature(t);
425 pdr->set_taken();
77047e76
JM
426}
427
1ad23cd3 428void TemperatureControl::set_desired_temperature(float desired_temperature)
cf1a7632 429{
7d4baeee
AW
430 // Never go over the configured max temperature
431 if( desired_temperature > this->max_temp ){
432 desired_temperature = this->max_temp;
433 }
434
08f89868 435 if (desired_temperature == 1.0F)
cf1a7632 436 desired_temperature = preset1;
08f89868 437 else if (desired_temperature == 2.0F)
cf1a7632
MM
438 desired_temperature = preset2;
439
08f89868 440 float last_target_temperature= target_temperature;
907d5e8a 441 target_temperature = desired_temperature;
3517edce 442 if (desired_temperature <= 0.0F){
08f89868 443 // turning it off
b35ac71e 444 heater_pin.set((this->o = 0));
08f89868 445
3517edce 446 }else if(last_target_temperature <= 0.0F) {
08f89868
JM
447 // if it was off and we are now turning it on we need to initialize
448 this->lastInput= last_reading;
449 // set to whatever the output currently is See http://brettbeauregard.com/blog/2011/04/improving-the-beginner%E2%80%99s-pid-initialization/
450 this->iTerm= this->o;
451 if (this->iTerm > this->i_max) this->iTerm = this->i_max;
452 else if (this->iTerm < 0.0) this->iTerm = 0.0;
453 }
fb778302
JM
454
455 // reset the runaway state, even if it was a temp change
456 this->runaway_state = NOT_HEATING;
ded56b35
AW
457}
458
4710532a
JM
459float TemperatureControl::get_temperature()
460{
907d5e8a 461 return last_reading;
ded56b35
AW
462}
463
4710532a
JM
464uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy)
465{
9d955060 466 float temperature = sensor->get_temperature();
3517edce 467 if(!this->readonly && target_temperature > 2) {
01004e36
JM
468 if (isinf(temperature) || temperature < min_temp || temperature > max_temp) {
469 this->temp_violated = true;
907d5e8a 470 target_temperature = UNDEFINED;
4710532a
JM
471 heater_pin.set((this->o = 0));
472 } else {
907d5e8a 473 pid_process(temperature);
ded56b35 474 }
959dc7db 475 }
3517edce 476
907d5e8a 477 last_reading = temperature;
281967e4 478 return 0;
ded56b35
AW
479}
480
10e66797
JM
481/**
482 * Based on https://github.com/br3ttb/Arduino-PID-Library
483 */
1ad23cd3 484void TemperatureControl::pid_process(float temperature)
907d5e8a 485{
989d0e94 486 if(use_bangbang) {
b35ac71e 487 // bang bang is very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
989d0e94 488 // good for relays
4710532a 489 if(temperature > (target_temperature + hysteresis) && this->o > 0) {
989d0e94 490 heater_pin.set(false);
4710532a 491 this->o = 0; // for display purposes only
989d0e94 492
4710532a 493 } else if(temperature < (target_temperature - hysteresis) && this->o <= 0) {
989d0e94
JM
494 if(heater_pin.max_pwm() >= 255) {
495 // turn on full
496 this->heater_pin.set(true);
4710532a
JM
497 this->o = 255; // for display purposes only
498 } else {
989d0e94
JM
499 // only to whatever max pwm is configured
500 this->heater_pin.pwm(heater_pin.max_pwm());
4710532a 501 this->o = heater_pin.max_pwm(); // for display purposes only
989d0e94 502 }
989d0e94
JM
503 }
504 return;
505 }
ded56b35 506
989d0e94
JM
507 // regular PID control
508 float error = target_temperature - temperature;
08f89868 509
0d84905d
PA
510 float new_I = this->iTerm + (error * this->i_factor);
511 if (new_I > this->i_max) new_I = this->i_max;
512 else if (new_I < 0.0) new_I = 0.0;
08f89868 513 if(!this->windup) this->iTerm= new_I;
ded56b35 514
4710532a 515 float d = (temperature - this->lastInput);
ded56b35 516
10e66797
JM
517 // calculate the PID output
518 // TODO does this need to be scaled by max_pwm/256? I think not as p_factor already does that
0d84905d 519 this->o = (this->p_factor * error) + new_I - (this->d_factor * d);
8cdae54c 520
7dee00e4 521 if (this->o >= heater_pin.max_pwm())
7dee00e4 522 this->o = heater_pin.max_pwm();
27aecda6 523 else if (this->o < 0)
907d5e8a 524 this->o = 0;
08f89868 525 else if(this->windup)
0d84905d 526 this->iTerm = new_I; // Only update I term when output is not saturated.
907d5e8a 527
27aecda6 528 this->heater_pin.pwm(this->o);
4710532a 529 this->lastInput = temperature;
907d5e8a 530}
ded56b35 531
4710532a 532void TemperatureControl::on_second_tick(void *argument)
8ccab7cf 533{
3bf54d11
AW
534
535 // If waiting for a temperature to be reach, display it to keep host programs up to date on the progress
8ccab7cf 536 if (waiting)
3517edce 537 THEKERNEL->streams->printf("%s:%3.1f /%3.1f @%d\n", designator.c_str(), get_temperature(), ((target_temperature <= 0) ? 0.0 : target_temperature), o);
3bf54d11
AW
538
539 // Check whether or not there is a temperature runaway issue, if so stop everything and report it
e39c48c1 540 if(THEKERNEL->is_halted()) return;
f967a81b 541
fb778302
JM
542 // see if runaway detection is enabled
543 if(this->runaway_heating_timeout == 0 && this->runaway_range == 0) return;
544
4f97f8b8
JM
545 // check every 8 seconds, depends on tick being 3 bits
546 if(++tick != 0) return;
547
fb778302 548 if(this->target_temperature <= 0){ // If we are not trying to heat, state is NOT_HEATING
c6c03d35 549 this->runaway_state = NOT_HEATING;
fb778302 550
3bf54d11 551 }else{
4f97f8b8 552 float current_temperature= this->get_temperature();
fb778302 553 // heater is active
3bf54d11 554 switch( this->runaway_state ){
c6c03d35 555 case NOT_HEATING: // If we were previously not trying to heat, but we are now, change to state WAITING_FOR_TEMP_TO_BE_REACHED
4f97f8b8
JM
556 this->runaway_state= (this->target_temperature > current_temperature) ? HEATING_UP : COOLING_DOWN;
557 this->runaway_timer = 0;
8123c72d 558 tick= 0;
3bf54d11 559 break;
fb778302 560
4f97f8b8
JM
561 case HEATING_UP:
562 case COOLING_DOWN:
563 if( (runaway_state == HEATING_UP && current_temperature >= this->target_temperature) ||
564 (runaway_state == COOLING_DOWN && current_temperature <= this->target_temperature) ) {
c6c03d35 565 this->runaway_state = TARGET_TEMPERATURE_REACHED;
4f97f8b8 566 this->runaway_timer = 0;
8123c72d 567 tick= 0;
fb778302 568
4f97f8b8
JM
569 }else{
570 uint16_t t= (runaway_state == HEATING_UP) ? this->runaway_heating_timeout : this->runaway_cooling_timeout;
fb778302 571 // we are still heating up see if we have hit the max time allowed
4f97f8b8 572 if(t > 0 && ++this->runaway_timer > t){
fb778302
JM
573 THEKERNEL->streams->printf("ERROR: Temperature took too long to be reached on %s, HALT asserted, TURN POWER OFF IMMEDIATELY - reset or M999 required\n", designator.c_str());
574 THEKERNEL->call_event(ON_HALT, nullptr);
575 this->runaway_state = NOT_HEATING;
4f97f8b8 576 this->runaway_timer = 0;
fb778302 577 }
3bf54d11
AW
578 }
579 break;
fb778302
JM
580
581 case TARGET_TEMPERATURE_REACHED:
582 if(this->runaway_range != 0) {
583 // we are in state TARGET_TEMPERATURE_REACHED, check for thermal runaway
4f97f8b8 584 float delta= current_temperature - this->target_temperature;
fb778302 585
4f97f8b8 586 // If the temperature is outside the acceptable range for 8 seconds, this allows for some noise spikes without halting
fb778302 587 if(fabsf(delta) > this->runaway_range){
4f97f8b8
JM
588 if(this->runaway_timer++ >= 1) { // this being 8 seconds
589 THEKERNEL->streams->printf("ERROR: Temperature runaway on %s (delta temp %f), HALT asserted, TURN POWER OFF IMMEDIATELY - reset or M999 required\n", designator.c_str(), delta);
590 THEKERNEL->call_event(ON_HALT, nullptr);
591 this->runaway_state = NOT_HEATING;
592 this->runaway_timer= 0;
593 }
fb778302
JM
594
595 }else{
4f97f8b8 596 this->runaway_timer= 0;
fb778302 597 }
3bf54d11 598 }
4f97f8b8 599
3bf54d11
AW
600 break;
601 }
602 }
8ccab7cf 603}
201e6dcf 604
4710532a
JM
605void TemperatureControl::setPIDp(float p)
606{
607 this->p_factor = p;
201e6dcf
JM
608}
609
4710532a
JM
610void TemperatureControl::setPIDi(float i)
611{
612 this->i_factor = i * this->PIDdt;
201e6dcf
JM
613}
614
4710532a
JM
615void TemperatureControl::setPIDd(float d)
616{
617 this->d_factor = d / this->PIDdt;
201e6dcf 618}