Merge remote-tracking branch 'upstream/edge' into upstreamedge
[clinton/Smoothieware.git] / src / modules / tools / temperaturecontrol / TemperatureControl.cpp
1 /*
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.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8 // TODO : THIS FILE IS LAME, MUST BE MADE MUCH BETTER
9
10 #include "libs/Module.h"
11 #include "libs/Kernel.h"
12 #include <math.h>
13 #include "TemperatureControl.h"
14 #include "TemperatureControlPool.h"
15 #include "libs/Pin.h"
16 #include "modules/robot/Conveyor.h"
17 #include "PublicDataRequest.h"
18 #include "TemperatureControlPublicAccess.h"
19 #include "StreamOutputPool.h"
20 #include "Config.h"
21 #include "checksumm.h"
22 #include "Gcode.h"
23 #include "SlowTicker.h"
24 #include "Pauser.h"
25 #include "ConfigValue.h"
26 #include "TemperatureControl.h"
27 #include "PID_Autotuner.h"
28
29 // Temp sensor implementations:
30 #include "Thermistor.h"
31 #include "max31855.h"
32
33 #include "MRI_Hooks.h"
34
35 #define UNDEFINED -1
36
37 #define sensor_checksum CHECKSUM("sensor")
38
39 #define readings_per_second_checksum CHECKSUM("readings_per_second")
40 #define max_pwm_checksum CHECKSUM("max_pwm")
41 #define pwm_frequency_checksum CHECKSUM("pwm_frequency")
42 #define bang_bang_checksum CHECKSUM("bang_bang")
43 #define hysteresis_checksum CHECKSUM("hysteresis")
44 #define heater_pin_checksum CHECKSUM("heater_pin")
45
46 #define get_m_code_checksum CHECKSUM("get_m_code")
47 #define set_m_code_checksum CHECKSUM("set_m_code")
48 #define set_and_wait_m_code_checksum CHECKSUM("set_and_wait_m_code")
49
50 #define designator_checksum CHECKSUM("designator")
51
52 #define p_factor_checksum CHECKSUM("p_factor")
53 #define i_factor_checksum CHECKSUM("i_factor")
54 #define d_factor_checksum CHECKSUM("d_factor")
55
56 #define i_max_checksum CHECKSUM("i_max")
57
58 #define preset1_checksum CHECKSUM("preset1")
59 #define preset2_checksum CHECKSUM("preset2")
60
61
62 TemperatureControl::TemperatureControl(uint16_t name) :
63 sensor(nullptr), name_checksum(name), waiting(false), min_temp_violated(false)
64 {
65 }
66
67 TemperatureControl::~TemperatureControl()
68 {
69 delete sensor;
70 }
71
72 void TemperatureControl::on_module_loaded(){
73
74 // We start not desiring any temp
75 this->target_temperature = UNDEFINED;
76
77 // Settings
78 this->on_config_reload(this);
79
80 // Register for events
81 register_for_event(ON_CONFIG_RELOAD);
82 this->register_for_event(ON_GCODE_EXECUTE);
83 this->register_for_event(ON_GCODE_RECEIVED);
84 this->register_for_event(ON_MAIN_LOOP);
85 this->register_for_event(ON_SECOND_TICK);
86 this->register_for_event(ON_GET_PUBLIC_DATA);
87 this->register_for_event(ON_SET_PUBLIC_DATA);
88 }
89
90 void TemperatureControl::on_main_loop(void* argument){
91 if (this->min_temp_violated) {
92 THEKERNEL->streams->printf("Error: MINTEMP triggered. Check your temperature sensors!\n");
93 this->min_temp_violated = false;
94 }
95 }
96
97 // Get configuration from the config file
98 void TemperatureControl::on_config_reload(void* argument){
99
100 // General config
101 this->set_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, set_m_code_checksum)->by_default(104)->as_number();
102 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();
103 this->get_m_code = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, get_m_code_checksum)->by_default(105)->as_number();
104 this->readings_per_second = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, readings_per_second_checksum)->by_default(20)->as_number();
105
106 this->designator = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, designator_checksum)->by_default(string("T"))->as_string();
107
108 // For backward compatibility, default to a thermistor sensor.
109 std::string sensor_type = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, sensor_checksum)->by_default("thermistor")->as_string();
110
111 // Instantiate correct sensor (TBD: TempSensor factory?)
112 delete sensor;
113 sensor = nullptr; // In case we fail to create a new sensor.
114 if(sensor_type.compare("thermistor") == 0)
115 {
116 sensor = new Thermistor();
117 }
118 else if(sensor_type.compare("max31855") == 0)
119 {
120 sensor = new Max31855();
121 }
122 else
123 {
124 sensor = new TempSensor(); // A dummy implementation
125 }
126 sensor->UpdateConfig(temperature_control_checksum, this->name_checksum);
127
128 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
129 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
130
131
132 // sigma-delta output modulation
133 this->o = 0;
134
135 // Heater pin
136 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->required()->as_string())->as_output();
137 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
138
139 this->heater_pin.set(0);
140
141 // used to enable bang bang control of heater
142 this->use_bangbang= THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
143 this->hysteresis= THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
144
145 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
146
147 // activate SD-DAC timer
148 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);
149
150 // reading tick
151 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
152 this->PIDdt= 1.0 / this->readings_per_second;
153
154 // PID
155 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
156 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
157 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
158 // set to the same as max_pwm by default
159 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
160 this->iTerm = 0.0;
161 this->lastInput= -1.0;
162 this->last_reading = 0.0;
163 }
164
165 void TemperatureControl::on_gcode_received(void* argument){
166 Gcode* gcode = static_cast<Gcode*>(argument);
167 if (gcode->has_m) {
168 // Get temperature
169 if( gcode->m == this->get_m_code ){
170 char buf[32]; // should be big enough for any status
171 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);
172 gcode->txt_after_ok.append(buf, n);
173 gcode->mark_as_taken();
174
175 } else if (gcode->m == 301) {
176 gcode->mark_as_taken();
177 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index))
178 {
179 if (gcode->has_letter('P'))
180 setPIDp( gcode->get_value('P') );
181 if (gcode->has_letter('I'))
182 setPIDi( gcode->get_value('I') );
183 if (gcode->has_letter('D'))
184 setPIDd( gcode->get_value('D') );
185 if (gcode->has_letter('X'))
186 this->i_max = gcode->get_value('X');
187 }
188 //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);
189 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);
190
191 } else if (gcode->m == 303) {
192 if (gcode->has_letter('E') && (gcode->get_value('E') == this->pool_index)) {
193 gcode->mark_as_taken();
194 float target = 150.0;
195 if (gcode->has_letter('S')) {
196 target = gcode->get_value('S');
197 gcode->stream->printf("Target: %5.1f\n", target);
198 }
199 int ncycles= 8;
200 if (gcode->has_letter('C')) {
201 ncycles= gcode->get_value('C');
202 }
203 gcode->stream->printf("Start PID tune, command is %s\n", gcode->command.c_str());
204 this->pool->PIDtuner->begin(this, target, gcode->stream, ncycles);
205 }
206
207 } else if (gcode->m == 500 || gcode->m == 503){// M500 saves some volatile settings to config override file, M503 just prints the settings
208 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);
209 gcode->mark_as_taken();
210
211 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S') ) {
212 // Attach gcodes to the last block for on_gcode_execute
213 THEKERNEL->conveyor->append_gcode(gcode);
214
215 // 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
216 if (gcode->m == this->set_and_wait_m_code)
217 // ensure that no subsequent gcodes get executed with our M109 or similar
218 THEKERNEL->conveyor->queue_head_block();
219 }
220 }
221 }
222
223 void TemperatureControl::on_gcode_execute(void* argument){
224 Gcode* gcode = static_cast<Gcode*>(argument);
225 if( gcode->has_m){
226 if (((gcode->m == this->set_m_code) || (gcode->m == this->set_and_wait_m_code))
227 && gcode->has_letter('S'))
228 {
229 float v = gcode->get_value('S');
230
231 if (v == 0.0)
232 {
233 this->target_temperature = UNDEFINED;
234 this->heater_pin.set((this->o=0));
235 }
236 else
237 {
238 this->set_desired_temperature(v);
239
240 if( gcode->m == this->set_and_wait_m_code)
241 {
242 THEKERNEL->pauser->take();
243 this->waiting = true;
244 }
245 }
246 }
247 }
248 }
249
250 void TemperatureControl::on_get_public_data(void* argument){
251 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
252
253 if(!pdr->starts_with(temperature_control_checksum)) return;
254
255 if(!pdr->second_element_is(this->name_checksum)) return; // will be bed or hotend
256
257 // ok this is targeted at us, so send back the requested data
258 if(pdr->third_element_is(current_temperature_checksum)) {
259 // this must be static as it will be accessed long after we have returned
260 static struct pad_temperature temp_return;
261 temp_return.current_temperature= this->get_temperature();
262 temp_return.target_temperature= (target_temperature == UNDEFINED) ? 0 : this->target_temperature;
263 temp_return.pwm= this->o;
264
265 pdr->set_data_ptr(&temp_return);
266 pdr->set_taken();
267 }
268 }
269
270 void TemperatureControl::on_set_public_data(void* argument){
271 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
272
273 if(!pdr->starts_with(temperature_control_checksum)) return;
274
275 if(!pdr->second_element_is(this->name_checksum)) return; // will be bed or hotend
276
277 // ok this is targeted at us, so set the temp
278 float t= *static_cast<float*>(pdr->get_data_ptr());
279 this->set_desired_temperature(t);
280 pdr->set_taken();
281 }
282
283 void TemperatureControl::set_desired_temperature(float desired_temperature)
284 {
285 if (desired_temperature == 1.0)
286 desired_temperature = preset1;
287 else if (desired_temperature == 2.0)
288 desired_temperature = preset2;
289
290 target_temperature = desired_temperature;
291 if (desired_temperature == 0.0)
292 heater_pin.set((this->o = 0));
293 }
294
295 float TemperatureControl::get_temperature(){
296 return last_reading;
297 }
298
299 uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy){
300 float temperature = sensor->get_temperature();
301
302 if (target_temperature > 0)
303 {
304 if (isinf(temperature))
305 {
306 this->min_temp_violated = true;
307 target_temperature = UNDEFINED;
308 heater_pin.set((this->o=0));
309 }
310 else
311 {
312 pid_process(temperature);
313 if ((temperature > target_temperature) && waiting)
314 {
315 THEKERNEL->pauser->release();
316 waiting = false;
317 }
318 }
319 }
320 else
321 {
322 heater_pin.set((this->o = 0));
323 }
324 last_reading = temperature;
325 return 0;
326 }
327
328 /**
329 * Based on https://github.com/br3ttb/Arduino-PID-Library
330 */
331 void TemperatureControl::pid_process(float temperature)
332 {
333 if(use_bangbang) {
334 // bang bang is very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
335 // good for relays
336 if(temperature > (target_temperature+hysteresis) && this->o > 0) {
337 heater_pin.set(false);
338 this->o= 0; // for display purposes only
339
340 }else if(temperature < (target_temperature-hysteresis) && this->o <= 0) {
341 if(heater_pin.max_pwm() >= 255) {
342 // turn on full
343 this->heater_pin.set(true);
344 this->o= 255; // for display purposes only
345 }else{
346 // only to whatever max pwm is configured
347 this->heater_pin.pwm(heater_pin.max_pwm());
348 this->o= heater_pin.max_pwm(); // for display purposes only
349 }
350 }
351 return;
352 }
353
354 // regular PID control
355 float error = target_temperature - temperature;
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;
359
360 if(this->lastInput < 0.0) this->lastInput= temperature; // set first time
361 float d= (temperature - this->lastInput);
362
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
365 this->o = (this->p_factor*error) + this->iTerm - (this->d_factor*d);
366
367 if (this->o >= heater_pin.max_pwm())
368 this->o = heater_pin.max_pwm();
369 else if (this->o < 0)
370 this->o = 0;
371
372 this->heater_pin.pwm(this->o);
373 this->lastInput= temperature;
374 }
375
376 void TemperatureControl::on_second_tick(void* argument)
377 {
378 if (waiting)
379 THEKERNEL->streams->printf("%s:%3.1f /%3.1f @%d\n", designator.c_str(), get_temperature(), ((target_temperature == UNDEFINED)?0.0:target_temperature), o);
380 }
381
382 void TemperatureControl::setPIDp(float p) {
383 this->p_factor= p;
384 }
385
386 void TemperatureControl::setPIDi(float i) {
387 this->i_factor= i*this->PIDdt;
388 }
389
390 void TemperatureControl::setPIDd(float d) {
391 this->d_factor= d/this->PIDdt;
392 }