Merge pull request #353 from wolfmanjm/cleanup/headers
[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 "libs/Median.h"
17 #include "modules/robot/Conveyor.h"
18 #include "PublicDataRequest.h"
19 #include "TemperatureControlPublicAccess.h"
20 #include "StreamOutputPool.h"
21 #include "Config.h"
22 #include "checksumm.h"
23 #include "Gcode.h"
24 #include "Adc.h"
25 #include "SlowTicker.h"
26 #include "Pauser.h"
27 #include "ConfigValue.h"
28 #include "TemperatureControl.h"
29 #include "PID_Autotuner.h"
30
31 #include "MRI_Hooks.h"
32
33 #define UNDEFINED -1
34
35 #define thermistor_checksum CHECKSUM("thermistor")
36 #define r0_checksum CHECKSUM("r0")
37 #define readings_per_second_checksum CHECKSUM("readings_per_second")
38 #define max_pwm_checksum CHECKSUM("max_pwm")
39 #define pwm_frequency_checksum CHECKSUM("pwm_frequency")
40 #define bang_bang_checksum CHECKSUM("bang_bang")
41 #define hysteresis_checksum CHECKSUM("hysteresis")
42 #define t0_checksum CHECKSUM("t0")
43 #define beta_checksum CHECKSUM("beta")
44 #define vadc_checksum CHECKSUM("vadc")
45 #define vcc_checksum CHECKSUM("vcc")
46 #define r1_checksum CHECKSUM("r1")
47 #define r2_checksum CHECKSUM("r2")
48 #define thermistor_pin_checksum CHECKSUM("thermistor_pin")
49 #define heater_pin_checksum CHECKSUM("heater_pin")
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")
62
63 #define preset1_checksum CHECKSUM("preset1")
64 #define preset2_checksum CHECKSUM("preset2")
65
66
67 TemperatureControl::TemperatureControl(uint16_t name) :
68 name_checksum(name), waiting(false), min_temp_violated(false) {}
69
70 void TemperatureControl::on_module_loaded(){
71
72 // We start not desiring any temp
73 this->target_temperature = UNDEFINED;
74
75 // Settings
76 this->on_config_reload(this);
77
78 this->acceleration_factor = 10;
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 on P%d.%d! check your thermistors!\n", this->thermistor_pin.port_number, this->thermistor_pin.pin);
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 // Values are here : http://reprap.org/wiki/Thermistor
109 this->r0 = 100000;
110 this->t0 = 25;
111 this->beta = 4066;
112 this->r1 = 0;
113 this->r2 = 4700;
114
115 // Preset values for various common types of thermistors
116 ConfigValue* thermistor = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, thermistor_checksum);
117 if( thermistor->value.compare("EPCOS100K" ) == 0 ){ // Default
118 }else if( thermistor->value.compare("RRRF100K" ) == 0 ){ this->beta = 3960;
119 }else if( thermistor->value.compare("RRRF10K" ) == 0 ){ this->beta = 3964; this->r0 = 10000; this->r1 = 680; this->r2 = 1600;
120 }else if( thermistor->value.compare("Honeywell100K") == 0 ){ this->beta = 3974;
121 }else if( thermistor->value.compare("Semitec" ) == 0 ){ this->beta = 4267;
122 }else if( thermistor->value.compare("HT100K" ) == 0 ){ this->beta = 3990; }
123
124 // Preset values are overriden by specified values
125 this->r0 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, r0_checksum )->by_default(this->r0 )->as_number(); // Stated resistance eg. 100K
126 this->t0 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, t0_checksum )->by_default(this->t0 )->as_number(); // Temperature at stated resistance, eg. 25C
127 this->beta = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, beta_checksum)->by_default(this->beta)->as_number(); // Thermistor beta rating. See http://reprap.org/bin/view/Main/MeasuringThermistorBeta
128 this->r1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, r1_checksum )->by_default(this->r1 )->as_number();
129 this->r2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, r2_checksum )->by_default(this->r2 )->as_number();
130
131 this->preset1 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset1_checksum)->by_default(0)->as_number();
132 this->preset2 = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, preset2_checksum)->by_default(0)->as_number();
133
134
135 // Thermistor math
136 j = (1.0 / beta);
137 k = (1.0 / (t0 + 273.15));
138
139 // sigma-delta output modulation
140 o = 0;
141
142 // Thermistor pin for ADC readings
143 this->thermistor_pin.from_string(THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, thermistor_pin_checksum )->required()->as_string());
144 THEKERNEL->adc->enable_pin(&thermistor_pin);
145
146 // Heater pin
147 this->heater_pin.from_string( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, heater_pin_checksum)->required()->as_string())->as_output();
148 this->heater_pin.max_pwm( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, max_pwm_checksum)->by_default(255)->as_number() );
149
150 this->heater_pin.set(0);
151 this->heater_on= false;
152
153 // used to enable bang bang control of heater
154 this->use_bangbang= THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, bang_bang_checksum)->by_default(false)->as_bool();
155 this->hysteresis= THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, hysteresis_checksum)->by_default(2)->as_number();
156
157 set_low_on_debug(heater_pin.port_number, heater_pin.pin);
158
159 // activate SD-DAC timer
160 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);
161
162 // reading tick
163 THEKERNEL->slow_ticker->attach( this->readings_per_second, this, &TemperatureControl::thermistor_read_tick );
164 this->PIDdt= 1.0 / this->readings_per_second;
165
166 // PID
167 setPIDp( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, p_factor_checksum)->by_default(10 )->as_number() );
168 setPIDi( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_factor_checksum)->by_default(0.3f)->as_number() );
169 setPIDd( THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, d_factor_checksum)->by_default(200)->as_number() );
170 // set to the same as max_pwm by default
171 this->i_max = THEKERNEL->config->value(temperature_control_checksum, this->name_checksum, i_max_checksum )->by_default(this->heater_pin.max_pwm())->as_number();
172 this->iTerm = 0.0;
173 this->lastInput= -1.0;
174 this->last_reading = 0.0;
175 }
176
177 void TemperatureControl::on_gcode_received(void* argument){
178 Gcode* gcode = static_cast<Gcode*>(argument);
179 if (gcode->has_m) {
180 // Get temperature
181 if( gcode->m == this->get_m_code ){
182 char buf[32]; // should be big enough for any status
183 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);
184 gcode->txt_after_ok.append(buf, n);
185 gcode->mark_as_taken();
186
187 } else if (gcode->m == 301) {
188 gcode->mark_as_taken();
189 if (gcode->has_letter('S') && (gcode->get_value('S') == this->pool_index))
190 {
191 if (gcode->has_letter('P'))
192 setPIDp( gcode->get_value('P') );
193 if (gcode->has_letter('I'))
194 setPIDi( gcode->get_value('I') );
195 if (gcode->has_letter('D'))
196 setPIDd( gcode->get_value('D') );
197 if (gcode->has_letter('X'))
198 this->i_max = gcode->get_value('X');
199 }
200 //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);
201 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);
202
203 } else if (gcode->m == 303) {
204 if (gcode->has_letter('E') && (gcode->get_value('E') == this->pool_index)) {
205 gcode->mark_as_taken();
206 float target = 150.0;
207 if (gcode->has_letter('S')) {
208 target = gcode->get_value('S');
209 gcode->stream->printf("Target: %5.1f\n", target);
210 }
211 int ncycles= 8;
212 if (gcode->has_letter('C')) {
213 ncycles= gcode->get_value('C');
214 }
215 gcode->stream->printf("Start PID tune, command is %s\n", gcode->command.c_str());
216 this->pool->PIDtuner->begin(this, target, gcode->stream, ncycles);
217 }
218
219 } else if (gcode->m == 500 || gcode->m == 503){// M500 saves some volatile settings to config override file, M503 just prints the settings
220 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);
221 gcode->mark_as_taken();
222
223 } else if( ( gcode->m == this->set_m_code || gcode->m == this->set_and_wait_m_code ) && gcode->has_letter('S') ) {
224 // Attach gcodes to the last block for on_gcode_execute
225 THEKERNEL->conveyor->append_gcode(gcode);
226
227 // 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
228 if (gcode->m == this->set_and_wait_m_code)
229 // ensure that no subsequent gcodes get executed with our M109 or similar
230 THEKERNEL->conveyor->queue_head_block();
231 }
232 }
233 }
234
235 void TemperatureControl::on_gcode_execute(void* argument){
236 Gcode* gcode = static_cast<Gcode*>(argument);
237 if( gcode->has_m){
238 if (((gcode->m == this->set_m_code) || (gcode->m == this->set_and_wait_m_code))
239 && gcode->has_letter('S'))
240 {
241 float v = gcode->get_value('S');
242
243 if (v == 0.0)
244 {
245 this->target_temperature = UNDEFINED;
246 this->heater_pin.set(0);
247 }
248 else
249 {
250 this->set_desired_temperature(v);
251
252 if( gcode->m == this->set_and_wait_m_code)
253 {
254 THEKERNEL->pauser->take();
255 this->waiting = true;
256 }
257 }
258 }
259 }
260 }
261
262 void TemperatureControl::on_get_public_data(void* argument){
263 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
264
265 if(!pdr->starts_with(temperature_control_checksum)) return;
266
267 if(!pdr->second_element_is(this->name_checksum)) return; // will be bed or hotend
268
269 // ok this is targeted at us, so send back the requested data
270 if(pdr->third_element_is(current_temperature_checksum)) {
271 // this must be static as it will be accessed long after we have returned
272 static struct pad_temperature temp_return;
273 temp_return.current_temperature= this->get_temperature();
274 temp_return.target_temperature= (target_temperature == UNDEFINED) ? 0 : this->target_temperature;
275 temp_return.pwm= this->o;
276
277 pdr->set_data_ptr(&temp_return);
278 pdr->set_taken();
279 }
280 }
281
282 void TemperatureControl::on_set_public_data(void* argument){
283 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
284
285 if(!pdr->starts_with(temperature_control_checksum)) return;
286
287 if(!pdr->second_element_is(this->name_checksum)) return; // will be bed or hotend
288
289 // ok this is targeted at us, so set the temp
290 float t= *static_cast<float*>(pdr->get_data_ptr());
291 this->set_desired_temperature(t);
292 pdr->set_taken();
293 }
294
295 void TemperatureControl::set_desired_temperature(float desired_temperature)
296 {
297 if (desired_temperature == 1.0)
298 desired_temperature = preset1;
299 else if (desired_temperature == 2.0)
300 desired_temperature = preset2;
301
302 target_temperature = desired_temperature;
303 if (desired_temperature == 0.0)
304 heater_pin.set((o = 0));
305 }
306
307 float TemperatureControl::get_temperature(){
308 return last_reading;
309 }
310
311 float TemperatureControl::adc_value_to_temperature(int adc_value)
312 {
313 if ((adc_value == 4095) || (adc_value == 0))
314 return INFINITY;
315 float r = r2 / ((4095.0 / adc_value) - 1.0);
316 if (r1 > 0)
317 r = (r1 * r) / (r1 - r);
318 return (1.0 / (k + (j * log(r / r0)))) - 273.15;
319 }
320
321 uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy){
322 int r = new_thermistor_reading();
323
324 float temperature = adc_value_to_temperature(r);
325
326 if (target_temperature > 0)
327 {
328 if ((r <= 1) || (r >= 4094))
329 {
330 this->min_temp_violated = true;
331 target_temperature = UNDEFINED;
332 heater_pin.set(0);
333 }
334 else
335 {
336 pid_process(temperature);
337 if ((temperature > target_temperature) && waiting)
338 {
339 THEKERNEL->pauser->release();
340 waiting = false;
341 }
342 }
343 }
344 else
345 {
346 heater_pin.set((o = 0));
347 }
348 last_reading = temperature;
349 return 0;
350 }
351
352 /**
353 * Based on https://github.com/br3ttb/Arduino-PID-Library
354 */
355 void TemperatureControl::pid_process(float temperature)
356 {
357 if(use_bangbang) {
358 // bang bang if very simple, if temp is < target - hysteresis turn on full else if temp is > target + hysteresis turn heater off
359 // good for relays
360 if(temperature > target_temperature+hysteresis && heater_on) {
361 heater_pin.set(false);
362 heater_on= false;
363 this->o= 0; // for display purposes only
364
365 }else if(temperature < target_temperature-hysteresis && !heater_on) {
366 if(heater_pin.max_pwm() >= 255) {
367 // turn on full
368 this->heater_pin.set(true);
369 this->o= 255; // for display purposes only
370 }else{
371 // only to whatever max pwm is configured
372 this->heater_pin.pwm(heater_pin.max_pwm());
373 this->o= heater_pin.max_pwm(); // for display purposes only
374 }
375 heater_on= true;
376 }
377 return;
378 }
379
380 // regular PID control
381 float error = target_temperature - temperature;
382 this->iTerm += (error * this->i_factor);
383 if (this->iTerm > this->i_max) this->iTerm = this->i_max;
384 else if (this->iTerm < 0.0) this->iTerm = 0.0;
385
386 if(this->lastInput < 0.0) this->lastInput= temperature; // set first time
387 float d= (temperature - this->lastInput);
388
389 // calculate the PID output
390 // TODO does this need to be scaled by max_pwm/256? I think not as p_factor already does that
391 this->o = (this->p_factor*error) + this->iTerm - (this->d_factor*d);
392
393 if (this->o >= heater_pin.max_pwm())
394 this->o = heater_pin.max_pwm();
395 else if (this->o < 0)
396 this->o = 0;
397
398 this->heater_pin.pwm(this->o);
399 this->lastInput= temperature;
400 }
401
402 int TemperatureControl::new_thermistor_reading()
403 {
404 int last_raw = THEKERNEL->adc->read(&thermistor_pin);
405 if (queue.size() >= queue.capacity()) {
406 uint16_t l;
407 queue.pop_front(l);
408 }
409 uint16_t r = last_raw;
410 queue.push_back(r);
411 for (int i=0; i<queue.size(); i++)
412 median_buffer[i] = *queue.get_ref(i);
413 uint16_t m = median_buffer[quick_median(median_buffer, queue.size())];
414 return m;
415 }
416
417 void TemperatureControl::on_second_tick(void* argument)
418 {
419 if (waiting)
420 THEKERNEL->streams->printf("%s:%3.1f /%3.1f @%d\n", designator.c_str(), get_temperature(), ((target_temperature == UNDEFINED)?0.0:target_temperature), o);
421 }
422
423 void TemperatureControl::setPIDp(float p) {
424 this->p_factor= p;
425 }
426
427 void TemperatureControl::setPIDi(float i) {
428 this->i_factor= i*this->PIDdt;
429 }
430
431 void TemperatureControl::setPIDd(float d) {
432 this->d_factor= d/this->PIDdt;
433 }