print the temp delta on runaway alarm
[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
AW
68#define runaway_heating_timeout_checksum CHECKSUM("runaway_heating_timeout")
69
8e8b938e 70TemperatureControl::TemperatureControl(uint16_t name, int index)
d8baddd9 71{
8e8b938e
JM
72 name_checksum= name;
73 pool_index= index;
74 waiting= false;
01004e36 75 temp_violated= false;
8e8b938e 76 sensor= nullptr;
71cc73eb 77 readonly= false;
d8baddd9 78}
ded56b35 79
d8baddd9 80TemperatureControl::~TemperatureControl()
81{
82 delete sensor;
83}
4710532a
JM
84
85void TemperatureControl::on_module_loaded()
86{
907d5e8a 87
81b547a1 88 // We start not desiring any temp
907d5e8a 89 this->target_temperature = UNDEFINED;
f1e38d95 90 this->sensor_settings= false; // set to true if sensor settings have been overriden
ded56b35
AW
91
92 // Settings
71cc73eb 93 this->load_config();
ded56b35 94
ded56b35 95 // Register for events
b0be67b5 96 this->register_for_event(ON_GCODE_RECEIVED);
8293d443 97 this->register_for_event(ON_GET_PUBLIC_DATA);
71cc73eb
JM
98
99 if(!this->readonly) {
71cc73eb
JM
100 this->register_for_event(ON_SECOND_TICK);
101 this->register_for_event(ON_MAIN_LOOP);
102 this->register_for_event(ON_SET_PUBLIC_DATA);
103 this->register_for_event(ON_HALT);
104 }
3d1a4519
JM
105}
106
107void TemperatureControl::on_halt(void *arg)
108{
728477c4
JM
109 if(arg == nullptr) {
110 // turn off heater
111 this->o = 0;
112 this->heater_pin.set(0);
113 this->target_temperature = UNDEFINED;
114 }
ded56b35
AW
115}
116
4710532a
JM
117void TemperatureControl::on_main_loop(void *argument)
118{
01004e36
JM
119 if (this->temp_violated) {
120 this->temp_violated = false;
f967a81b 121 THEKERNEL->streams->printf("ERROR : MINTEMP or MAXTEMP triggered on %s. Check your temperature sensors!\n", designator.c_str());
01004e36
JM
122 THEKERNEL->streams->printf("HALT asserted - reset or M999 required\n");
123 THEKERNEL->call_event(ON_HALT, nullptr);
a7f12bed 124 }
7e57bc2c 125}
7dd8133c
AW
126
127// Get configuration from the config file
71cc73eb 128void TemperatureControl::load_config()
4710532a 129{
7dd8133c 130
1306ba99 131 // General config
314ab8f7
MM
132 this->set_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_m_code_checksum)->by_default(104)->as_number();
133 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();
134 this->get_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, get_m_code_checksum)->by_default(105)->as_number();
135 this->readings_per_second = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, readings_per_second_checksum)->by_default(20)->as_number();
7dee00e4 136
314ab8f7 137 this->designator = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, designator_checksum)->by_default(string("T"))->as_string();
b0be67b5 138
1cd1bf1a
AW
139 // Runaway parameters
140 this->runaway_range = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, runaway_range_checksum)->by_default(0)->as_number();
1cd1bf1a
AW
141 this->runaway_heating_timeout = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, runaway_heating_timeout_checksum)->by_default(0)->as_number();
142
3a014cbb 143 // Max and min temperatures we are not allowed to get over (Safety)
01004e36 144 this->max_temp = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_temp_checksum)->by_default(300)->as_number();
3a014cbb 145 this->min_temp = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, min_temp_checksum)->by_default(0)->as_number();
7d4baeee 146
71cc73eb
JM
147 // Heater pin
148 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->by_default("nc")->as_string());
149 if(this->heater_pin.connected()){
150 this->readonly= false;
151 this->heater_pin.as_output();
152
153 } else {
154 this->readonly= true;
155 }
156
d8baddd9 157 // For backward compatibility, default to a thermistor sensor.
158 std::string sensor_type = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, sensor_checksum)->by_default("thermistor")->as_string();
159
160 // Instantiate correct sensor (TBD: TempSensor factory?)
161 delete sensor;
162 sensor = nullptr; // In case we fail to create a new sensor.
4710532a 163 if(sensor_type.compare("thermistor") == 0) {
d8baddd9 164 sensor = new Thermistor();
4710532a 165 } else if(sensor_type.compare("max31855") == 0) {
d8baddd9 166 sensor = new Max31855();
073d88ec
E
167 } else if(sensor_type.compare("ad8495") == 0) {
168 sensor = new AD8495();
4710532a 169 } else {
d8baddd9 170 sensor = new TempSensor(); // A dummy implementation
171 }
172 sensor->UpdateConfig(temperature_control_checksum, this->name_checksum);
4710532a 173
71cc73eb
JM
174 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
175 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
f4bd4fc3 176
907d5e8a 177
c4f4cf73 178 // sigma-delta output modulation
b35ac71e 179 this->o = 0;
3c132bd0 180
71cc73eb
JM
181 if(!this->readonly) {
182 // used to enable bang bang control of heater
183 this->use_bangbang = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
184 this->hysteresis = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
08f89868 185 this->windup = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, windup_checksum)->by_default(false)->as_bool();
71cc73eb
JM
186 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
187 this->heater_pin.set(0);
188 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
189 // activate SD-DAC timer
190 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);
191 }
8f91e4e6 192
907d5e8a 193
f39da6fe 194 // reading tick
314ab8f7 195 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
4710532a 196 this->PIDdt = 1.0 / this->readings_per_second;
f39da6fe 197
907d5e8a 198 // PID
314ab8f7 199 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
1ad23cd3 200 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
314ab8f7 201 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
71cc73eb
JM
202
203 if(!this->readonly) {
204 // set to the same as max_pwm by default
205 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
206 }
207
10e66797 208 this->iTerm = 0.0;
4710532a 209 this->lastInput = -1.0;
907d5e8a 210 this->last_reading = 0.0;
7dd8133c
AW
211}
212
4710532a
JM
213void TemperatureControl::on_gcode_received(void *argument)
214{
215 Gcode *gcode = static_cast<Gcode *>(argument);
8dfbc976 216 if (gcode->has_m) {
ee4711d1 217
4710532a 218 if( gcode->m == this->get_m_code ) {
93284f6f 219 char buf[32]; // should be big enough for any status
3517edce 220 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 221 gcode->txt_after_ok.append(buf, n);
71cc73eb
JM
222 return;
223 }
8dfbc976 224
76f53dc6 225 if (gcode->m == 305) { // set or get sensor settings
76f53dc6 226 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
1f8dab1a 227 TempSensor::sensor_options_t args= gcode->get_args();
d22755f7
JM
228 args.erase('S'); // don't include the S
229 if(args.size() > 0) {
76f53dc6 230 // set the new options
d22755f7
JM
231 if(sensor->set_optional(args)) {
232 this->sensor_settings= true;
233 }else{
234 gcode->stream->printf("Unable to properly set sensor settings, make sure you specify all required values\n");
235 }
236 }else{
237 // don't override
238 this->sensor_settings= false;
76f53dc6
JM
239 }
240
241 }else if(!gcode->has_letter('S')) {
d22755f7 242 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
243 sensor->get_raw();
244 TempSensor::sensor_options_t options;
245 if(sensor->get_optional(options)) {
246 for(auto &i : options) {
247 // foreach optional value
a2e5f877 248 gcode->stream->printf("%s(S%d): %c %1.18f\n", this->designator.c_str(), this->pool_index, i.first, i.second);
76f53dc6
JM
249 }
250 }
251 }
252
253 return;
254 }
255
71cc73eb
JM
256 // readonly sensors don't handle the rest
257 if(this->readonly) return;
258
01004e36
JM
259 if (gcode->m == 143) {
260 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
261 if(gcode->has_letter('P')) {
262 max_temp= gcode->get_value('P');
263
264 } else {
265 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");
266 }
267
268 }else if(gcode->get_num_args() == 0) {
269 gcode->stream->printf("Maximum temperature for %s(%d) is %f°C\n", this->designator.c_str(), this->pool_index, max_temp);
270 }
271
272 } else if (gcode->m == 301) {
4710532a 273 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
827a49ca 274 if (gcode->has_letter('P'))
201e6dcf 275 setPIDp( gcode->get_value('P') );
827a49ca 276 if (gcode->has_letter('I'))
201e6dcf 277 setPIDi( gcode->get_value('I') );
827a49ca 278 if (gcode->has_letter('D'))
201e6dcf 279 setPIDd( gcode->get_value('D') );
827a49ca 280 if (gcode->has_letter('X'))
f1e38d95
JM
281 this->i_max = gcode->get_value('X');
282 if (gcode->has_letter('Y'))
283 this->heater_pin.max_pwm(gcode->get_value('Y'));
284
285 }else if(!gcode->has_letter('S')) {
286 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);
287 }
288
4710532a 289 } else if (gcode->m == 500 || gcode->m == 503) { // M500 saves some volatile settings to config override file, M503 just prints the settings
f1e38d95
JM
290 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());
291
01004e36
JM
292 gcode->stream->printf(";Max temperature setting:\nM143 S%d P%1.4f\n", this->pool_index, this->max_temp);
293
f1e38d95
JM
294 if(this->sensor_settings) {
295 // get or save any sensor specific optional values
296 TempSensor::sensor_options_t options;
297 if(sensor->get_optional(options) && !options.empty()) {
298 gcode->stream->printf(";Optional temp sensor specific settings:\nM305 S%d", this->pool_index);
299 for(auto &i : options) {
7d678d16 300 gcode->stream->printf(" %c%1.18f", i.first, i.second);
f1e38d95
JM
301 }
302 gcode->stream->printf("\n");
303 }
304 }
33e4cc02 305
8e8b938e 306 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S')) {
42cb1b30 307 // this only gets handled if it is not controlled by the tool manager or is active in the toolmanager
8e8b938e
JM
308 this->active = true;
309
310 // this is safe as old configs as well as single extruder configs the toolmanager will not be running so will return false
311 // this will also ignore anything that the tool manager is not controlling and return false, otherwise it returns the active tool
312 void *returned_data;
75e6428d 313 bool ok = PublicData::get_value( tool_manager_checksum, is_active_tool_checksum, this->name_checksum, &returned_data );
8e8b938e
JM
314 if (ok) {
315 uint16_t active_tool_name = *static_cast<uint16_t *>(returned_data);
316 this->active = (active_tool_name == this->name_checksum);
317 }
318
319 if(this->active) {
42cb1b30 320 // required so temp change happens in order
04782655 321 THEKERNEL->conveyor->wait_for_idle();
2134bcf2 322
42cb1b30 323 float v = gcode->get_value('S');
db453125 324
42cb1b30
JM
325 if (v == 0.0) {
326 this->target_temperature = UNDEFINED;
327 this->heater_pin.set((this->o = 0));
328 } else {
329 this->set_desired_temperature(v);
ed52bf31
JM
330 // wait for temp to be reached, no more gcodes will be fetched until this is complete
331 if( gcode->m == this->set_and_wait_m_code) {
487976f7 332 if(isinf(get_temperature()) && isinf(sensor->get_temperature())) {
f0433db4 333 THEKERNEL->streams->printf("Temperature reading is unreliable on %s HALT asserted - reset or M999 required\n", designator.c_str());
487976f7
JM
334 THEKERNEL->call_event(ON_HALT, nullptr);
335 return;
336 }
337
ed52bf31
JM
338 this->waiting = true; // on_second_tick will announce temps
339 while ( get_temperature() < target_temperature ) {
340 THEKERNEL->call_event(ON_IDLE, this);
798295c1 341 // check if ON_HALT was called (usually by kill button)
aa896868
JM
342 if(THEKERNEL->is_halted() || this->target_temperature == UNDEFINED) {
343 THEKERNEL->streams->printf("Wait on temperature aborted by kill\n");
344 break;
345 }
ed52bf31
JM
346 }
347 this->waiting = false;
42cb1b30 348 }
cf1a7632 349 }
907d5e8a 350 }
df27a6a3 351 }
df27a6a3 352 }
ded56b35
AW
353}
354
4710532a
JM
355void TemperatureControl::on_get_public_data(void *argument)
356{
357 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
201e6dcf 358
b19aa09d
JM
359 if(!pdr->starts_with(temperature_control_checksum)) return;
360
8e8b938e
JM
361 if(pdr->second_element_is(pool_index_checksum)) {
362 // asking for our instance pointer if we have this pool_index
363 if(pdr->third_element_is(this->pool_index)) {
364 static void *return_data;
365 return_data = this;
366 pdr->set_data_ptr(&return_data);
367 pdr->set_taken();
368 }
8e8b938e 369
56a6c8c1 370 }else if(pdr->second_element_is(poll_controls_checksum)) {
bab4e1bd 371 // polling for all temperature controls
3bfb2639
JM
372 // add our data to the list which is passed in via the data_ptr
373
374 std::vector<struct pad_temperature> *v= static_cast<std::vector<pad_temperature>*>(pdr->get_data_ptr());
bab4e1bd 375
3bfb2639 376 struct pad_temperature t;
bab4e1bd 377 // setup data
3bfb2639
JM
378 t.current_temperature = this->get_temperature();
379 t.target_temperature = (target_temperature <= 0) ? 0 : this->target_temperature;
380 t.pwm = this->o;
381 t.designator= this->designator;
382 t.id= this->name_checksum;
383 v->push_back(t);
384 pdr->set_taken();
b19aa09d 385
56a6c8c1
JM
386 }else if(pdr->second_element_is(current_temperature_checksum)) {
387 // if targeted at us
388 if(pdr->third_element_is(this->name_checksum)) {
564cf1f0 389 // ok this is targeted at us, so set the requ3sted data in the pointer passed into us
56a6c8c1
JM
390 struct pad_temperature *t= static_cast<pad_temperature*>(pdr->get_data_ptr());
391 t->current_temperature = this->get_temperature();
392 t->target_temperature = (target_temperature <= 0) ? 0 : this->target_temperature;
393 t->pwm = this->o;
394 t->designator= this->designator;
395 t->id= this->name_checksum;
396 pdr->set_taken();
56a6c8c1 397 }
b19aa09d 398 }
8e8b938e 399
8293d443 400}
db453125 401
4710532a
JM
402void TemperatureControl::on_set_public_data(void *argument)
403{
404 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
77047e76 405
991d98cc 406 if(!pdr->starts_with(temperature_control_checksum)) return;
77047e76 407
8e8b938e 408 if(!pdr->second_element_is(this->name_checksum)) return;
77047e76 409
991d98cc 410 // ok this is targeted at us, so set the temp
ed52bf31 411 // NOTE unlike the M code this will set the temp now not when the queue is empty
4710532a 412 float t = *static_cast<float *>(pdr->get_data_ptr());
991d98cc
JM
413 this->set_desired_temperature(t);
414 pdr->set_taken();
77047e76
JM
415}
416
1ad23cd3 417void TemperatureControl::set_desired_temperature(float desired_temperature)
cf1a7632 418{
7d4baeee
AW
419 // Never go over the configured max temperature
420 if( desired_temperature > this->max_temp ){
421 desired_temperature = this->max_temp;
422 }
423
08f89868 424 if (desired_temperature == 1.0F)
cf1a7632 425 desired_temperature = preset1;
08f89868 426 else if (desired_temperature == 2.0F)
cf1a7632
MM
427 desired_temperature = preset2;
428
08f89868 429 float last_target_temperature= target_temperature;
907d5e8a 430 target_temperature = desired_temperature;
3517edce 431 if (desired_temperature <= 0.0F){
08f89868 432 // turning it off
b35ac71e 433 heater_pin.set((this->o = 0));
08f89868 434
3517edce 435 }else if(last_target_temperature <= 0.0F) {
08f89868
JM
436 // if it was off and we are now turning it on we need to initialize
437 this->lastInput= last_reading;
438 // set to whatever the output currently is See http://brettbeauregard.com/blog/2011/04/improving-the-beginner%E2%80%99s-pid-initialization/
439 this->iTerm= this->o;
440 if (this->iTerm > this->i_max) this->iTerm = this->i_max;
441 else if (this->iTerm < 0.0) this->iTerm = 0.0;
442 }
ded56b35
AW
443}
444
4710532a
JM
445float TemperatureControl::get_temperature()
446{
907d5e8a 447 return last_reading;
ded56b35
AW
448}
449
4710532a
JM
450uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy)
451{
9d955060 452 float temperature = sensor->get_temperature();
3517edce 453 if(!this->readonly && target_temperature > 2) {
01004e36
JM
454 if (isinf(temperature) || temperature < min_temp || temperature > max_temp) {
455 this->temp_violated = true;
907d5e8a 456 target_temperature = UNDEFINED;
4710532a
JM
457 heater_pin.set((this->o = 0));
458 } else {
907d5e8a 459 pid_process(temperature);
ded56b35 460 }
959dc7db 461 }
3517edce 462
907d5e8a 463 last_reading = temperature;
281967e4 464 return 0;
ded56b35
AW
465}
466
10e66797
JM
467/**
468 * Based on https://github.com/br3ttb/Arduino-PID-Library
469 */
1ad23cd3 470void TemperatureControl::pid_process(float temperature)
907d5e8a 471{
989d0e94 472 if(use_bangbang) {
b35ac71e 473 // bang bang is very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
989d0e94 474 // good for relays
4710532a 475 if(temperature > (target_temperature + hysteresis) && this->o > 0) {
989d0e94 476 heater_pin.set(false);
4710532a 477 this->o = 0; // for display purposes only
989d0e94 478
4710532a 479 } else if(temperature < (target_temperature - hysteresis) && this->o <= 0) {
989d0e94
JM
480 if(heater_pin.max_pwm() >= 255) {
481 // turn on full
482 this->heater_pin.set(true);
4710532a
JM
483 this->o = 255; // for display purposes only
484 } else {
989d0e94
JM
485 // only to whatever max pwm is configured
486 this->heater_pin.pwm(heater_pin.max_pwm());
4710532a 487 this->o = heater_pin.max_pwm(); // for display purposes only
989d0e94 488 }
989d0e94
JM
489 }
490 return;
491 }
ded56b35 492
989d0e94
JM
493 // regular PID control
494 float error = target_temperature - temperature;
08f89868 495
0d84905d
PA
496 float new_I = this->iTerm + (error * this->i_factor);
497 if (new_I > this->i_max) new_I = this->i_max;
498 else if (new_I < 0.0) new_I = 0.0;
08f89868 499 if(!this->windup) this->iTerm= new_I;
ded56b35 500
4710532a 501 float d = (temperature - this->lastInput);
ded56b35 502
10e66797
JM
503 // calculate the PID output
504 // TODO does this need to be scaled by max_pwm/256? I think not as p_factor already does that
0d84905d 505 this->o = (this->p_factor * error) + new_I - (this->d_factor * d);
8cdae54c 506
7dee00e4 507 if (this->o >= heater_pin.max_pwm())
7dee00e4 508 this->o = heater_pin.max_pwm();
27aecda6 509 else if (this->o < 0)
907d5e8a 510 this->o = 0;
08f89868 511 else if(this->windup)
0d84905d 512 this->iTerm = new_I; // Only update I term when output is not saturated.
907d5e8a 513
27aecda6 514 this->heater_pin.pwm(this->o);
4710532a 515 this->lastInput = temperature;
907d5e8a 516}
ded56b35 517
4710532a 518void TemperatureControl::on_second_tick(void *argument)
8ccab7cf 519{
3bf54d11
AW
520
521 // If waiting for a temperature to be reach, display it to keep host programs up to date on the progress
8ccab7cf 522 if (waiting)
3517edce 523 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
524
525 // Check whether or not there is a temperature runaway issue, if so stop everything and report it
e39c48c1 526 if(THEKERNEL->is_halted()) return;
f967a81b 527
c6c03d35
AW
528 if( this->target_temperature <= 0 ){ // If we are not trying to heat, state is NOT_HEATING
529 this->runaway_state = NOT_HEATING;
3bf54d11
AW
530 }else{
531 switch( this->runaway_state ){
c6c03d35 532 case NOT_HEATING: // If we were previously not trying to heat, but we are now, change to state WAITING_FOR_TEMP_TO_BE_REACHED
3bf54d11 533 if( this->target_temperature > 0 ){
c6c03d35
AW
534 this->runaway_state = WAITING_FOR_TEMP_TO_BE_REACHED;
535 this->runaway_heating_timer = 0;
3bf54d11
AW
536 }
537 break;
c6c03d35 538 case WAITING_FOR_TEMP_TO_BE_REACHED: // In we are in state 1 ( waiting for temperature to be reached ), and the temperature has been reached, change to state TARGET_TEMPERATURE_REACHED
3bf54d11 539 if( this->get_temperature() >= this->target_temperature ){
c6c03d35
AW
540 this->runaway_state = TARGET_TEMPERATURE_REACHED;
541 }
542 this->runaway_heating_timer++;
1cd1bf1a 543 if( this->runaway_heating_timer > this->runaway_heating_timeout && this->runaway_heating_timeout != 0 ){
c6c03d35 544 this->runaway_heating_timer = 0;
f967a81b 545 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());
c6c03d35 546 THEKERNEL->call_event(ON_HALT, nullptr);
3bf54d11
AW
547 }
548 break;
f967a81b
JM
549 case TARGET_TEMPERATURE_REACHED: { // If we are in state TARGET_TEMPERATURE_REACHED, check for thermal runaway
550 float delta= this->get_temperature() - this->target_temperature;
3bf54d11 551 // If the temperature is outside the acceptable range
f967a81b
JM
552 if(this->runaway_range != 0 && fabsf(delta) > this->runaway_range){
553 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);
dd81c6dd 554 THEKERNEL->call_event(ON_HALT, nullptr);
3bf54d11 555 }
f967a81b 556 }
3bf54d11
AW
557 break;
558 }
559 }
8ccab7cf 560}
201e6dcf 561
4710532a
JM
562void TemperatureControl::setPIDp(float p)
563{
564 this->p_factor = p;
201e6dcf
JM
565}
566
4710532a
JM
567void TemperatureControl::setPIDi(float i)
568{
569 this->i_factor = i * this->PIDdt;
201e6dcf
JM
570}
571
4710532a
JM
572void TemperatureControl::setPIDd(float d)
573{
574 this->d_factor = d / this->PIDdt;
201e6dcf 575}