Merge pull request #411 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
JM
28#include "TemperatureControl.h"
29#include "PID_Autotuner.h"
ded56b35 30
9d955060 31// Temp sensor implementations:
32#include "Thermistor.h"
4710532a 33#include "max31855.h"
9d955060 34
8f91e4e6
MM
35#include "MRI_Hooks.h"
36
85eabc50
JM
37#define UNDEFINED -1
38
9d955060 39#define sensor_checksum CHECKSUM("sensor")
40
85eabc50
JM
41#define readings_per_second_checksum CHECKSUM("readings_per_second")
42#define max_pwm_checksum CHECKSUM("max_pwm")
43#define pwm_frequency_checksum CHECKSUM("pwm_frequency")
989d0e94
JM
44#define bang_bang_checksum CHECKSUM("bang_bang")
45#define hysteresis_checksum CHECKSUM("hysteresis")
85eabc50
JM
46#define heater_pin_checksum CHECKSUM("heater_pin")
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")
59
60#define preset1_checksum CHECKSUM("preset1")
61#define preset2_checksum CHECKSUM("preset2")
62
7e57bc2c 63TemperatureControl::TemperatureControl(uint16_t name) :
4710532a 64 sensor(nullptr), name_checksum(name), waiting(false), min_temp_violated(false)
d8baddd9 65{
66}
ded56b35 67
d8baddd9 68TemperatureControl::~TemperatureControl()
69{
70 delete sensor;
71}
4710532a
JM
72
73void TemperatureControl::on_module_loaded()
74{
907d5e8a 75
81b547a1 76 // We start not desiring any temp
907d5e8a 77 this->target_temperature = UNDEFINED;
ded56b35
AW
78
79 // Settings
7dd8133c 80 this->on_config_reload(this);
ded56b35 81
ded56b35 82 // Register for events
476dcb96 83 register_for_event(ON_CONFIG_RELOAD);
df27a6a3 84 this->register_for_event(ON_GCODE_EXECUTE);
b0be67b5 85 this->register_for_event(ON_GCODE_RECEIVED);
df27a6a3 86 this->register_for_event(ON_MAIN_LOOP);
8ccab7cf 87 this->register_for_event(ON_SECOND_TICK);
8293d443 88 this->register_for_event(ON_GET_PUBLIC_DATA);
991d98cc 89 this->register_for_event(ON_SET_PUBLIC_DATA);
ded56b35
AW
90}
91
4710532a
JM
92void TemperatureControl::on_main_loop(void *argument)
93{
7e57bc2c 94 if (this->min_temp_violated) {
9d955060 95 THEKERNEL->streams->printf("Error: MINTEMP triggered. Check your temperature sensors!\n");
7e57bc2c 96 this->min_temp_violated = false;
a7f12bed 97 }
7e57bc2c 98}
7dd8133c
AW
99
100// Get configuration from the config file
4710532a
JM
101void TemperatureControl::on_config_reload(void *argument)
102{
7dd8133c 103
1306ba99 104 // General config
314ab8f7
MM
105 this->set_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_m_code_checksum)->by_default(104)->as_number();
106 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();
107 this->get_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, get_m_code_checksum)->by_default(105)->as_number();
108 this->readings_per_second = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, readings_per_second_checksum)->by_default(20)->as_number();
7dee00e4 109
314ab8f7 110 this->designator = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, designator_checksum)->by_default(string("T"))->as_string();
b0be67b5 111
d8baddd9 112 // For backward compatibility, default to a thermistor sensor.
113 std::string sensor_type = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, sensor_checksum)->by_default("thermistor")->as_string();
114
115 // Instantiate correct sensor (TBD: TempSensor factory?)
116 delete sensor;
117 sensor = nullptr; // In case we fail to create a new sensor.
4710532a 118 if(sensor_type.compare("thermistor") == 0) {
d8baddd9 119 sensor = new Thermistor();
4710532a 120 } else if(sensor_type.compare("max31855") == 0) {
d8baddd9 121 sensor = new Max31855();
4710532a 122 } else {
d8baddd9 123 sensor = new TempSensor(); // A dummy implementation
124 }
125 sensor->UpdateConfig(temperature_control_checksum, this->name_checksum);
4710532a 126
314ab8f7
MM
127 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
128 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
f4bd4fc3 129
907d5e8a 130
c4f4cf73 131 // sigma-delta output modulation
b35ac71e 132 this->o = 0;
3c132bd0 133
3c132bd0 134 // Heater pin
314ab8f7
MM
135 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->required()->as_string())->as_output();
136 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
989d0e94 137
7dee00e4 138 this->heater_pin.set(0);
989d0e94
JM
139
140 // used to enable bang bang control of heater
4710532a
JM
141 this->use_bangbang = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
142 this->hysteresis = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
7dd8133c 143
cb3460e9 144 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
8f91e4e6 145
907d5e8a 146 // activate SD-DAC timer
314ab8f7 147 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);
907d5e8a 148
f39da6fe 149 // reading tick
314ab8f7 150 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
4710532a 151 this->PIDdt = 1.0 / this->readings_per_second;
f39da6fe 152
907d5e8a 153 // PID
314ab8f7 154 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
1ad23cd3 155 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
314ab8f7 156 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
10e66797 157 // set to the same as max_pwm by default
314ab8f7 158 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
10e66797 159 this->iTerm = 0.0;
4710532a 160 this->lastInput = -1.0;
907d5e8a 161 this->last_reading = 0.0;
7dd8133c
AW
162}
163
4710532a
JM
164void TemperatureControl::on_gcode_received(void *argument)
165{
166 Gcode *gcode = static_cast<Gcode *>(argument);
8dfbc976 167 if (gcode->has_m) {
b0be67b5 168 // Get temperature
18551e1f 169 this->active = true;
ee4711d1
JM
170
171 // this is safe as old configs the toolmanager will not be running anyway as well as in single extruder configs
172 void *returned_data;
173 bool ok = THEKERNEL->public_data->get_value( tool_manager_checksum, &returned_data );
174 if (ok) {
175 struct pad_toolmanager toolmanager = *static_cast<struct pad_toolmanager *>(returned_data);
176 this->active = toolmanager.current_tool_name == this->name_checksum;
38b9f24a 177 }
ee4711d1 178
4710532a 179 if( gcode->m == this->get_m_code ) {
93284f6f 180 char buf[32]; // should be big enough for any status
4710532a 181 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 182 gcode->txt_after_ok.append(buf, n);
a24ab0ac 183 gcode->mark_as_taken();
8dfbc976
JM
184
185 } else if (gcode->m == 301) {
74b6303c 186 gcode->mark_as_taken();
4710532a 187 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index)) {
827a49ca 188 if (gcode->has_letter('P'))
201e6dcf 189 setPIDp( gcode->get_value('P') );
827a49ca 190 if (gcode->has_letter('I'))
201e6dcf 191 setPIDi( gcode->get_value('I') );
827a49ca 192 if (gcode->has_letter('D'))
201e6dcf 193 setPIDd( gcode->get_value('D') );
827a49ca
MM
194 if (gcode->has_letter('X'))
195 this->i_max = gcode->get_value('X');
196 }
10e66797 197 //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 198 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
JM
199
200 } else if (gcode->m == 303) {
201 if (gcode->has_letter('E') && (gcode->get_value('E') == this->pool_index)) {
202 gcode->mark_as_taken();
1ad23cd3 203 float target = 150.0;
8dfbc976
JM
204 if (gcode->has_letter('S')) {
205 target = gcode->get_value('S');
827a49ca
MM
206 gcode->stream->printf("Target: %5.1f\n", target);
207 }
4710532a 208 int ncycles = 8;
8dfbc976 209 if (gcode->has_letter('C')) {
4710532a 210 ncycles = gcode->get_value('C');
8dfbc976 211 }
827a49ca 212 gcode->stream->printf("Start PID tune, command is %s\n", gcode->command.c_str());
8dfbc976 213 this->pool->PIDtuner->begin(this, target, gcode->stream, ncycles);
827a49ca 214 }
cf1a7632 215
4710532a
JM
216 } else if (gcode->m == 500 || gcode->m == 503) { // M500 saves some volatile settings to config override file, M503 just prints the settings
217 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
218 gcode->mark_as_taken();
219
18551e1f 220 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S') && this->active ) {
8dfbc976 221 // Attach gcodes to the last block for on_gcode_execute
e0ee24ed 222 THEKERNEL->conveyor->append_gcode(gcode);
2134bcf2
MM
223
224 // 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
225 if (gcode->m == this->set_and_wait_m_code)
518e225f 226 // ensure that no subsequent gcodes get executed with our M109 or similar
2134bcf2 227 THEKERNEL->conveyor->queue_head_block();
3c4f2dd8 228 }
b0be67b5
MM
229 }
230}
db453125 231
4710532a
JM
232void TemperatureControl::on_gcode_execute(void *argument)
233{
234 Gcode *gcode = static_cast<Gcode *>(argument);
235 if( gcode->has_m) {
cf1a7632 236 if (((gcode->m == this->set_m_code) || (gcode->m == this->set_and_wait_m_code))
4710532a 237 && gcode->has_letter('S') && this->active) {
1ad23cd3 238 float v = gcode->get_value('S');
f4bd4fc3 239
4710532a 240 if (v == 0.0) {
907d5e8a 241 this->target_temperature = UNDEFINED;
4710532a
JM
242 this->heater_pin.set((this->o = 0));
243 } else {
f4bd4fc3 244 this->set_desired_temperature(v);
cf1a7632 245
4710532a 246 if( gcode->m == this->set_and_wait_m_code) {
314ab8f7 247 THEKERNEL->pauser->take();
cf1a7632
MM
248 this->waiting = true;
249 }
907d5e8a 250 }
df27a6a3 251 }
df27a6a3 252 }
ded56b35
AW
253}
254
4710532a
JM
255void TemperatureControl::on_get_public_data(void *argument)
256{
257 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
201e6dcf 258
b19aa09d
JM
259 if(!pdr->starts_with(temperature_control_checksum)) return;
260
261 if(!pdr->second_element_is(this->name_checksum)) return; // will be bed or hotend
262
263 // ok this is targeted at us, so send back the requested data
264 if(pdr->third_element_is(current_temperature_checksum)) {
2fa50ca0
JM
265 this->public_data_return.current_temperature = this->get_temperature();
266 this->public_data_return.target_temperature = (target_temperature == UNDEFINED) ? 0 : this->target_temperature;
267 this->public_data_return.pwm = this->o;
268 this->public_data_return.designator= this->designator;
269 pdr->set_data_ptr(&this->public_data_return);
b19aa09d
JM
270 pdr->set_taken();
271 }
8293d443 272}
db453125 273
4710532a
JM
274void TemperatureControl::on_set_public_data(void *argument)
275{
276 PublicDataRequest *pdr = static_cast<PublicDataRequest *>(argument);
77047e76 277
991d98cc 278 if(!pdr->starts_with(temperature_control_checksum)) return;
77047e76 279
991d98cc 280 if(!pdr->second_element_is(this->name_checksum)) return; // will be bed or hotend
77047e76 281
991d98cc 282 // ok this is targeted at us, so set the temp
4710532a 283 float t = *static_cast<float *>(pdr->get_data_ptr());
991d98cc
JM
284 this->set_desired_temperature(t);
285 pdr->set_taken();
77047e76
JM
286}
287
1ad23cd3 288void TemperatureControl::set_desired_temperature(float desired_temperature)
cf1a7632
MM
289{
290 if (desired_temperature == 1.0)
291 desired_temperature = preset1;
292 else if (desired_temperature == 2.0)
293 desired_temperature = preset2;
294
907d5e8a 295 target_temperature = desired_temperature;
959dc7db 296 if (desired_temperature == 0.0)
b35ac71e 297 heater_pin.set((this->o = 0));
ded56b35
AW
298}
299
4710532a
JM
300float TemperatureControl::get_temperature()
301{
907d5e8a 302 return last_reading;
ded56b35
AW
303}
304
4710532a
JM
305uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy)
306{
9d955060 307 float temperature = sensor->get_temperature();
907d5e8a 308
4710532a
JM
309 if (target_temperature > 0) {
310 if (isinf(temperature)) {
7e57bc2c 311 this->min_temp_violated = true;
907d5e8a 312 target_temperature = UNDEFINED;
4710532a
JM
313 heater_pin.set((this->o = 0));
314 } else {
907d5e8a 315 pid_process(temperature);
4710532a 316 if ((temperature > target_temperature) && waiting) {
347854ff 317 THEKERNEL->pauser->release();
907d5e8a 318 waiting = false;
81b547a1 319 }
ded56b35 320 }
4710532a 321 } else {
b35ac71e 322 heater_pin.set((this->o = 0));
959dc7db 323 }
907d5e8a 324 last_reading = temperature;
281967e4 325 return 0;
ded56b35
AW
326}
327
10e66797
JM
328/**
329 * Based on https://github.com/br3ttb/Arduino-PID-Library
330 */
1ad23cd3 331void TemperatureControl::pid_process(float temperature)
907d5e8a 332{
989d0e94 333 if(use_bangbang) {
b35ac71e 334 // bang bang is very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
989d0e94 335 // good for relays
4710532a 336 if(temperature > (target_temperature + hysteresis) && this->o > 0) {
989d0e94 337 heater_pin.set(false);
4710532a 338 this->o = 0; // for display purposes only
989d0e94 339
4710532a 340 } else if(temperature < (target_temperature - hysteresis) && this->o <= 0) {
989d0e94
JM
341 if(heater_pin.max_pwm() >= 255) {
342 // turn on full
343 this->heater_pin.set(true);
4710532a
JM
344 this->o = 255; // for display purposes only
345 } else {
989d0e94
JM
346 // only to whatever max pwm is configured
347 this->heater_pin.pwm(heater_pin.max_pwm());
4710532a 348 this->o = heater_pin.max_pwm(); // for display purposes only
989d0e94 349 }
989d0e94
JM
350 }
351 return;
352 }
ded56b35 353
989d0e94
JM
354 // regular PID control
355 float error = target_temperature - temperature;
10e66797
JM
356 this->iTerm += (error * this->i_factor);
357 if (this->iTerm > this->i_max) this->iTerm = this->i_max;
358 else if (this->iTerm < 0.0) this->iTerm = 0.0;
ded56b35 359
4710532a
JM
360 if(this->lastInput < 0.0) this->lastInput = temperature; // set first time
361 float d = (temperature - this->lastInput);
ded56b35 362
10e66797
JM
363 // calculate the PID output
364 // TODO does this need to be scaled by max_pwm/256? I think not as p_factor already does that
4710532a 365 this->o = (this->p_factor * error) + this->iTerm - (this->d_factor * d);
8cdae54c 366
7dee00e4 367 if (this->o >= heater_pin.max_pwm())
7dee00e4 368 this->o = heater_pin.max_pwm();
27aecda6 369 else if (this->o < 0)
907d5e8a
MM
370 this->o = 0;
371
27aecda6 372 this->heater_pin.pwm(this->o);
4710532a 373 this->lastInput = temperature;
907d5e8a 374}
ded56b35 375
4710532a 376void TemperatureControl::on_second_tick(void *argument)
8ccab7cf
MM
377{
378 if (waiting)
4710532a 379 THEKERNEL->streams->printf("%s:%3.1f /%3.1f @%d\n", designator.c_str(), get_temperature(), ((target_temperature == UNDEFINED) ? 0.0 : target_temperature), o);
8ccab7cf 380}
201e6dcf 381
4710532a
JM
382void TemperatureControl::setPIDp(float p)
383{
384 this->p_factor = p;
201e6dcf
JM
385}
386
4710532a
JM
387void TemperatureControl::setPIDi(float i)
388{
389 this->i_factor = i * this->PIDdt;
201e6dcf
JM
390}
391
4710532a
JM
392void TemperatureControl::setPIDd(float d)
393{
394 this->d_factor = d / this->PIDdt;
201e6dcf 395}