Merge pull request #570 from wolfmanjm/upstreamedge
[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
JM
25#include "SlowTicker.h"
26#include "Pauser.h"
8d54c34c 27#include "ConfigValue.h"
66383b80 28#include "PID_Autotuner.h"
ded56b35 29
9d955060 30// Temp sensor implementations:
31#include "Thermistor.h"
4710532a 32#include "max31855.h"
9d955060 33
8f91e4e6
MM
34#include "MRI_Hooks.h"
35
85eabc50
JM
36#define UNDEFINED -1
37
9d955060 38#define sensor_checksum CHECKSUM("sensor")
39
85eabc50
JM
40#define readings_per_second_checksum CHECKSUM("readings_per_second")
41#define max_pwm_checksum CHECKSUM("max_pwm")
42#define pwm_frequency_checksum CHECKSUM("pwm_frequency")
989d0e94
JM
43#define bang_bang_checksum CHECKSUM("bang_bang")
44#define hysteresis_checksum CHECKSUM("hysteresis")
85eabc50 45#define heater_pin_checksum CHECKSUM("heater_pin")
bb02929e 46#define max_temp_checksum CHECKSUM("max_temp")
85eabc50
JM
47
48#define get_m_code_checksum CHECKSUM("get_m_code")
49#define set_m_code_checksum CHECKSUM("set_m_code")
50#define set_and_wait_m_code_checksum CHECKSUM("set_and_wait_m_code")
51
52#define designator_checksum CHECKSUM("designator")
53
54#define p_factor_checksum CHECKSUM("p_factor")
55#define i_factor_checksum CHECKSUM("i_factor")
56#define d_factor_checksum CHECKSUM("d_factor")
57
58#define i_max_checksum CHECKSUM("i_max")
08f89868 59#define windup_checksum CHECKSUM("windup")
85eabc50
JM
60
61#define preset1_checksum CHECKSUM("preset1")
62#define preset2_checksum CHECKSUM("preset2")
63
8e8b938e 64TemperatureControl::TemperatureControl(uint16_t name, int index)
d8baddd9 65{
8e8b938e
JM
66 name_checksum= name;
67 pool_index= index;
68 waiting= false;
69 min_temp_violated= false;
70 sensor= nullptr;
71cc73eb 71 readonly= false;
d8baddd9 72}
ded56b35 73
d8baddd9 74TemperatureControl::~TemperatureControl()
75{
76 delete sensor;
77}
4710532a
JM
78
79void TemperatureControl::on_module_loaded()
80{
907d5e8a 81
81b547a1 82 // We start not desiring any temp
907d5e8a 83 this->target_temperature = UNDEFINED;
ded56b35
AW
84
85 // Settings
71cc73eb 86 this->load_config();
ded56b35 87
ded56b35 88 // Register for events
b0be67b5 89 this->register_for_event(ON_GCODE_RECEIVED);
8293d443 90 this->register_for_event(ON_GET_PUBLIC_DATA);
71cc73eb
JM
91
92 if(!this->readonly) {
93 this->register_for_event(ON_GCODE_EXECUTE);
94 this->register_for_event(ON_SECOND_TICK);
95 this->register_for_event(ON_MAIN_LOOP);
96 this->register_for_event(ON_SET_PUBLIC_DATA);
97 this->register_for_event(ON_HALT);
98 }
3d1a4519
JM
99}
100
101void TemperatureControl::on_halt(void *arg)
102{
728477c4
JM
103 if(arg == nullptr) {
104 // turn off heater
105 this->o = 0;
106 this->heater_pin.set(0);
107 this->target_temperature = UNDEFINED;
108 }
ded56b35
AW
109}
110
4710532a
JM
111void TemperatureControl::on_main_loop(void *argument)
112{
7e57bc2c 113 if (this->min_temp_violated) {
9d955060 114 THEKERNEL->streams->printf("Error: MINTEMP triggered. Check your temperature sensors!\n");
7e57bc2c 115 this->min_temp_violated = false;
a7f12bed 116 }
7e57bc2c 117}
7dd8133c
AW
118
119// Get configuration from the config file
71cc73eb 120void TemperatureControl::load_config()
4710532a 121{
7dd8133c 122
1306ba99 123 // General config
314ab8f7
MM
124 this->set_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_m_code_checksum)->by_default(104)->as_number();
125 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();
126 this->get_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, get_m_code_checksum)->by_default(105)->as_number();
127 this->readings_per_second = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, readings_per_second_checksum)->by_default(20)->as_number();
7dee00e4 128
314ab8f7 129 this->designator = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, designator_checksum)->by_default(string("T"))->as_string();
b0be67b5 130
7d4baeee
AW
131 // Max temperature we are not allowed to get over
132 this->max_temp = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_temp_checksum)->by_default(1000)->as_number();
133
71cc73eb
JM
134 // Heater pin
135 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->by_default("nc")->as_string());
136 if(this->heater_pin.connected()){
137 this->readonly= false;
138 this->heater_pin.as_output();
139
140 } else {
141 this->readonly= true;
142 }
143
d8baddd9 144 // For backward compatibility, default to a thermistor sensor.
145 std::string sensor_type = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, sensor_checksum)->by_default("thermistor")->as_string();
146
147 // Instantiate correct sensor (TBD: TempSensor factory?)
148 delete sensor;
149 sensor = nullptr; // In case we fail to create a new sensor.
4710532a 150 if(sensor_type.compare("thermistor") == 0) {
d8baddd9 151 sensor = new Thermistor();
4710532a 152 } else if(sensor_type.compare("max31855") == 0) {
d8baddd9 153 sensor = new Max31855();
4710532a 154 } else {
d8baddd9 155 sensor = new TempSensor(); // A dummy implementation
156 }
157 sensor->UpdateConfig(temperature_control_checksum, this->name_checksum);
4710532a 158
71cc73eb
JM
159 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
160 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
f4bd4fc3 161
907d5e8a 162
c4f4cf73 163 // sigma-delta output modulation
b35ac71e 164 this->o = 0;
3c132bd0 165
71cc73eb
JM
166 if(!this->readonly) {
167 // used to enable bang bang control of heater
168 this->use_bangbang = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
169 this->hysteresis = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
08f89868 170 this->windup = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, windup_checksum)->by_default(false)->as_bool();
71cc73eb
JM
171 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
172 this->heater_pin.set(0);
173 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
174 // activate SD-DAC timer
175 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);
176 }
8f91e4e6 177
907d5e8a 178
f39da6fe 179 // reading tick
314ab8f7 180 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
4710532a 181 this->PIDdt = 1.0 / this->readings_per_second;
f39da6fe 182
907d5e8a 183 // PID
314ab8f7 184 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
1ad23cd3 185 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
314ab8f7 186 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
71cc73eb
JM
187
188 if(!this->readonly) {
189 // set to the same as max_pwm by default
190 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
191 }
192
10e66797 193 this->iTerm = 0.0;
4710532a 194 this->lastInput = -1.0;
907d5e8a 195 this->last_reading = 0.0;
7dd8133c
AW
196}
197
4710532a
JM
198void TemperatureControl::on_gcode_received(void *argument)
199{
200 Gcode *gcode = static_cast<Gcode *>(argument);
8dfbc976 201 if (gcode->has_m) {
ee4711d1 202
4710532a 203 if( gcode->m == this->get_m_code ) {
93284f6f 204 char buf[32]; // should be big enough for any status
4710532a 205 int n = snprintf(buf, sizeof(buf), "%s:%3.1f /%3.1f @%d ", this->designator.c_str(), this->get_temperature(), ((target_temperature == UNDEFINED) ? 0.0 : target_temperature), this->o);
93284f6f 206 gcode->txt_after_ok.append(buf, n);
a24ab0ac 207 gcode->mark_as_taken();
71cc73eb
JM
208 return;
209 }
8dfbc976 210
71cc73eb
JM
211 // readonly sensors don't handle the rest
212 if(this->readonly) return;
213
214 if (gcode->m == 301) {
74b6303c 215 gcode->mark_as_taken();
4710532a 216 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
827a49ca 217 if (gcode->has_letter('P'))
201e6dcf 218 setPIDp( gcode->get_value('P') );
827a49ca 219 if (gcode->has_letter('I'))
201e6dcf 220 setPIDi( gcode->get_value('I') );
827a49ca 221 if (gcode->has_letter('D'))
201e6dcf 222 setPIDd( gcode->get_value('D') );
827a49ca
MM
223 if (gcode->has_letter('X'))
224 this->i_max = gcode->get_value('X');
225 }
10e66797 226 //gcode->stream->printf("%s(S%d): Pf:%g If:%g Df:%g X(I_max):%g Pv:%g Iv:%g Dv:%g 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->p, this->i, this->d, o);
4710532a 227 gcode->stream->printf("%s(S%d): Pf:%g If:%g Df:%g X(I_max):%g 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, o);
8dfbc976 228
4710532a
JM
229 } else if (gcode->m == 500 || gcode->m == 503) { // M500 saves some volatile settings to config override file, M503 just prints the settings
230 gcode->stream->printf(";PID settings:\nM301 S%d P%1.4f I%1.4f D%1.4f\n", this->pool_index, this->p_factor, this->i_factor / this->PIDdt, this->d_factor * this->PIDdt);
33e4cc02
JM
231 gcode->mark_as_taken();
232
8e8b938e
JM
233 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S')) {
234 // this only gets handled if it is not controlle dby the tool manager or is active in the toolmanager
235 this->active = true;
236
237 // this is safe as old configs as well as single extruder configs the toolmanager will not be running so will return false
238 // this will also ignore anything that the tool manager is not controlling and return false, otherwise it returns the active tool
239 void *returned_data;
75e6428d 240 bool ok = PublicData::get_value( tool_manager_checksum, is_active_tool_checksum, this->name_checksum, &returned_data );
8e8b938e
JM
241 if (ok) {
242 uint16_t active_tool_name = *static_cast<uint16_t *>(returned_data);
243 this->active = (active_tool_name == this->name_checksum);
244 }
245
246 if(this->active) {
247 // Attach gcodes to the last block for on_gcode_execute
248 THEKERNEL->conveyor->append_gcode(gcode);
2134bcf2 249
8e8b938e
JM
250 // push an empty block if we have to wait, so the Planner can get things right, and we can prevent subsequent non-move gcodes from executing
251 if (gcode->m == this->set_and_wait_m_code) {
252 // ensure that no subsequent gcodes get executed with our M109 or similar
253 THEKERNEL->conveyor->queue_head_block();
254 }
255 }
3c4f2dd8 256 }
b0be67b5
MM
257 }
258}
db453125 259
4710532a
JM
260void TemperatureControl::on_gcode_execute(void *argument)
261{
262 Gcode *gcode = static_cast<Gcode *>(argument);
263 if( gcode->has_m) {
cf1a7632 264 if (((gcode->m == this->set_m_code) || (gcode->m == this->set_and_wait_m_code))
4710532a 265 && gcode->has_letter('S') && this->active) {
1ad23cd3 266 float v = gcode->get_value('S');
f4bd4fc3 267
4710532a 268 if (v == 0.0) {
907d5e8a 269 this->target_temperature = UNDEFINED;
4710532a
JM
270 this->heater_pin.set((this->o = 0));
271 } else {
f4bd4fc3 272 this->set_desired_temperature(v);
cf1a7632 273
7dc903db 274 if( gcode->m == this->set_and_wait_m_code && !this->waiting) {
314ab8f7 275 THEKERNEL->pauser->take();
cf1a7632
MM
276 this->waiting = true;
277 }
907d5e8a 278 }
df27a6a3 279 }
df27a6a3 280 }
ded56b35
AW
281}
282
4710532a
JM
283void TemperatureControl::on_get_public_data(void *argument)
284{
285 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
201e6dcf 286
b19aa09d
JM
287 if(!pdr->starts_with(temperature_control_checksum)) return;
288
8e8b938e
JM
289 if(pdr->second_element_is(pool_index_checksum)) {
290 // asking for our instance pointer if we have this pool_index
291 if(pdr->third_element_is(this->pool_index)) {
292 static void *return_data;
293 return_data = this;
294 pdr->set_data_ptr(&return_data);
295 pdr->set_taken();
296 }
297 return;
298
299 }else if(!pdr->second_element_is(this->name_checksum)) return;
b19aa09d
JM
300
301 // ok this is targeted at us, so send back the requested data
302 if(pdr->third_element_is(current_temperature_checksum)) {
2fa50ca0
JM
303 this->public_data_return.current_temperature = this->get_temperature();
304 this->public_data_return.target_temperature = (target_temperature == UNDEFINED) ? 0 : this->target_temperature;
305 this->public_data_return.pwm = this->o;
306 this->public_data_return.designator= this->designator;
307 pdr->set_data_ptr(&this->public_data_return);
b19aa09d
JM
308 pdr->set_taken();
309 }
8e8b938e 310
8293d443 311}
db453125 312
4710532a
JM
313void TemperatureControl::on_set_public_data(void *argument)
314{
315 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
77047e76 316
991d98cc 317 if(!pdr->starts_with(temperature_control_checksum)) return;
77047e76 318
8e8b938e 319 if(!pdr->second_element_is(this->name_checksum)) return;
77047e76 320
991d98cc 321 // ok this is targeted at us, so set the temp
4710532a 322 float t = *static_cast<float *>(pdr->get_data_ptr());
991d98cc
JM
323 this->set_desired_temperature(t);
324 pdr->set_taken();
77047e76
JM
325}
326
1ad23cd3 327void TemperatureControl::set_desired_temperature(float desired_temperature)
cf1a7632 328{
7d4baeee
AW
329 // Never go over the configured max temperature
330 if( desired_temperature > this->max_temp ){
331 desired_temperature = this->max_temp;
332 }
333
08f89868 334 if (desired_temperature == 1.0F)
cf1a7632 335 desired_temperature = preset1;
08f89868 336 else if (desired_temperature == 2.0F)
cf1a7632
MM
337 desired_temperature = preset2;
338
08f89868 339 float last_target_temperature= target_temperature;
907d5e8a 340 target_temperature = desired_temperature;
08f89868
JM
341 if (desired_temperature == 0.0F){
342 // turning it off
b35ac71e 343 heater_pin.set((this->o = 0));
08f89868
JM
344
345 }else if(last_target_temperature == 0.0F) {
346 // if it was off and we are now turning it on we need to initialize
347 this->lastInput= last_reading;
348 // set to whatever the output currently is See http://brettbeauregard.com/blog/2011/04/improving-the-beginner%E2%80%99s-pid-initialization/
349 this->iTerm= this->o;
350 if (this->iTerm > this->i_max) this->iTerm = this->i_max;
351 else if (this->iTerm < 0.0) this->iTerm = 0.0;
352 }
ded56b35
AW
353}
354
4710532a
JM
355float TemperatureControl::get_temperature()
356{
907d5e8a 357 return last_reading;
ded56b35
AW
358}
359
4710532a
JM
360uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy)
361{
9d955060 362 float temperature = sensor->get_temperature();
71cc73eb
JM
363 if(this->readonly) {
364 last_reading = temperature;
365 return 0;
366 }
907d5e8a 367
4710532a
JM
368 if (target_temperature > 0) {
369 if (isinf(temperature)) {
7e57bc2c 370 this->min_temp_violated = true;
907d5e8a 371 target_temperature = UNDEFINED;
4710532a
JM
372 heater_pin.set((this->o = 0));
373 } else {
907d5e8a 374 pid_process(temperature);
02e4b295 375 if ( waiting && (temperature >= target_temperature) ) {
347854ff 376 THEKERNEL->pauser->release();
907d5e8a 377 waiting = false;
81b547a1 378 }
ded56b35 379 }
4710532a 380 } else {
b35ac71e 381 heater_pin.set((this->o = 0));
959dc7db 382 }
907d5e8a 383 last_reading = temperature;
281967e4 384 return 0;
ded56b35
AW
385}
386
10e66797
JM
387/**
388 * Based on https://github.com/br3ttb/Arduino-PID-Library
389 */
1ad23cd3 390void TemperatureControl::pid_process(float temperature)
907d5e8a 391{
989d0e94 392 if(use_bangbang) {
b35ac71e 393 // bang bang is very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
989d0e94 394 // good for relays
4710532a 395 if(temperature > (target_temperature + hysteresis) && this->o > 0) {
989d0e94 396 heater_pin.set(false);
4710532a 397 this->o = 0; // for display purposes only
989d0e94 398
4710532a 399 } else if(temperature < (target_temperature - hysteresis) && this->o <= 0) {
989d0e94
JM
400 if(heater_pin.max_pwm() >= 255) {
401 // turn on full
402 this->heater_pin.set(true);
4710532a
JM
403 this->o = 255; // for display purposes only
404 } else {
989d0e94
JM
405 // only to whatever max pwm is configured
406 this->heater_pin.pwm(heater_pin.max_pwm());
4710532a 407 this->o = heater_pin.max_pwm(); // for display purposes only
989d0e94 408 }
989d0e94
JM
409 }
410 return;
411 }
ded56b35 412
989d0e94
JM
413 // regular PID control
414 float error = target_temperature - temperature;
08f89868 415
0d84905d
PA
416 float new_I = this->iTerm + (error * this->i_factor);
417 if (new_I > this->i_max) new_I = this->i_max;
418 else if (new_I < 0.0) new_I = 0.0;
08f89868 419 if(!this->windup) this->iTerm= new_I;
ded56b35 420
4710532a 421 float d = (temperature - this->lastInput);
ded56b35 422
10e66797
JM
423 // calculate the PID output
424 // TODO does this need to be scaled by max_pwm/256? I think not as p_factor already does that
0d84905d 425 this->o = (this->p_factor * error) + new_I - (this->d_factor * d);
8cdae54c 426
7dee00e4 427 if (this->o >= heater_pin.max_pwm())
7dee00e4 428 this->o = heater_pin.max_pwm();
27aecda6 429 else if (this->o < 0)
907d5e8a 430 this->o = 0;
08f89868 431 else if(this->windup)
0d84905d 432 this->iTerm = new_I; // Only update I term when output is not saturated.
907d5e8a 433
27aecda6 434 this->heater_pin.pwm(this->o);
4710532a 435 this->lastInput = temperature;
907d5e8a 436}
ded56b35 437
4710532a 438void TemperatureControl::on_second_tick(void *argument)
8ccab7cf
MM
439{
440 if (waiting)
4710532a 441 THEKERNEL->streams->printf("%s:%3.1f /%3.1f @%d\n", designator.c_str(), get_temperature(), ((target_temperature == UNDEFINED) ? 0.0 : target_temperature), o);
8ccab7cf 442}
201e6dcf 443
4710532a
JM
444void TemperatureControl::setPIDp(float p)
445{
446 this->p_factor = p;
201e6dcf
JM
447}
448
4710532a
JM
449void TemperatureControl::setPIDi(float i)
450{
451 this->i_factor = i * this->PIDdt;
201e6dcf
JM
452}
453
4710532a
JM
454void TemperatureControl::setPIDd(float d)
455{
456 this->d_factor = d / this->PIDdt;
201e6dcf 457}