Subversion Repositories MK-Marlin

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 ron 1
/**
2
 * Marlin 3D Printer Firmware
3
 * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
 *
5
 * Based on Sprinter and grbl.
6
 * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
 
23
/**
24
 * temperature.cpp - temperature control
25
 */
26
 
27
#include "Marlin.h"
28
#include "temperature.h"
29
#include "thermistortables.h"
30
#include "ultralcd.h"
31
#include "planner.h"
32
#include "language.h"
33
#include "printcounter.h"
34
#include "delay.h"
35
#include "endstops.h"
36
 
37
#if ENABLED(HEATER_0_USES_MAX6675)
38
  #include "MarlinSPI.h"
39
#endif
40
 
41
#if ENABLED(BABYSTEPPING)
42
  #include "stepper.h"
43
#endif
44
 
45
#if ENABLED(USE_WATCHDOG)
46
  #include "watchdog.h"
47
#endif
48
 
49
#if ENABLED(EMERGENCY_PARSER)
50
  #include "emergency_parser.h"
51
#endif
52
 
53
#if HOTEND_USES_THERMISTOR
54
  #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
55
    static void* heater_ttbl_map[2] = { (void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE };
56
    static constexpr uint8_t heater_ttbllen_map[2] = { HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN };
57
  #else
58
    static void* heater_ttbl_map[HOTENDS] = ARRAY_BY_HOTENDS((void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE, (void*)HEATER_2_TEMPTABLE, (void*)HEATER_3_TEMPTABLE, (void*)HEATER_4_TEMPTABLE);
59
    static constexpr uint8_t heater_ttbllen_map[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN, HEATER_3_TEMPTABLE_LEN, HEATER_4_TEMPTABLE_LEN);
60
  #endif
61
#endif
62
 
63
Temperature thermalManager;
64
 
65
/**
66
 * Macros to include the heater id in temp errors. The compiler's dead-code
67
 * elimination should (hopefully) optimize out the unused strings.
68
 */
69
#if HAS_HEATED_BED
70
  #define TEMP_ERR_PSTR(MSG, E) \
71
    (E) == -1 ? PSTR(MSG ## _BED) : \
72
    (HOTENDS > 1 && (E) == 1) ? PSTR(MSG_E2 " " MSG) : \
73
    (HOTENDS > 2 && (E) == 2) ? PSTR(MSG_E3 " " MSG) : \
74
    (HOTENDS > 3 && (E) == 3) ? PSTR(MSG_E4 " " MSG) : \
75
    (HOTENDS > 4 && (E) == 4) ? PSTR(MSG_E5 " " MSG) : \
76
    PSTR(MSG_E1 " " MSG)
77
#else
78
  #define TEMP_ERR_PSTR(MSG, E) \
79
    (HOTENDS > 1 && (E) == 1) ? PSTR(MSG_E2 " " MSG) : \
80
    (HOTENDS > 2 && (E) == 2) ? PSTR(MSG_E3 " " MSG) : \
81
    (HOTENDS > 3 && (E) == 3) ? PSTR(MSG_E4 " " MSG) : \
82
    (HOTENDS > 4 && (E) == 4) ? PSTR(MSG_E5 " " MSG) : \
83
    PSTR(MSG_E1 " " MSG)
84
#endif
85
 
86
// public:
87
 
88
float Temperature::current_temperature[HOTENDS] = { 0.0 };
89
int16_t Temperature::current_temperature_raw[HOTENDS] = { 0 },
90
        Temperature::target_temperature[HOTENDS] = { 0 };
91
 
92
#if ENABLED(AUTO_POWER_E_FANS)
93
  int16_t Temperature::autofan_speed[HOTENDS] = { 0 };
94
#endif
95
 
96
#if HAS_HEATED_BED
97
  float Temperature::current_temperature_bed = 0.0;
98
  int16_t Temperature::current_temperature_bed_raw = 0,
99
          Temperature::target_temperature_bed = 0;
100
  uint8_t Temperature::soft_pwm_amount_bed;
101
  #ifdef BED_MINTEMP
102
    int16_t Temperature::bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
103
  #endif
104
  #ifdef BED_MAXTEMP
105
    int16_t Temperature::bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
106
  #endif
107
  #if WATCH_THE_BED
108
    uint16_t Temperature::watch_target_bed_temp = 0;
109
    millis_t Temperature::watch_bed_next_ms = 0;
110
  #endif
111
  #if ENABLED(PIDTEMPBED)
112
    float Temperature::bedKp, Temperature::bedKi, Temperature::bedKd, // Initialized by settings.load()
113
          Temperature::temp_iState_bed = { 0 },
114
          Temperature::temp_dState_bed = { 0 },
115
          Temperature::pTerm_bed,
116
          Temperature::iTerm_bed,
117
          Temperature::dTerm_bed,
118
          Temperature::pid_error_bed;
119
  #else
120
    millis_t Temperature::next_bed_check_ms;
121
  #endif
122
  uint16_t Temperature::raw_temp_bed_value = 0;
123
  #if HEATER_IDLE_HANDLER
124
    millis_t Temperature::bed_idle_timeout_ms = 0;
125
    bool Temperature::bed_idle_timeout_exceeded = false;
126
  #endif
127
#endif // HAS_HEATED_BED
128
 
129
#if HAS_TEMP_CHAMBER
130
  float Temperature::current_temperature_chamber = 0.0;
131
  int16_t Temperature::current_temperature_chamber_raw = 0;
132
  uint16_t Temperature::raw_temp_chamber_value = 0;
133
#endif
134
 
135
// Initialized by settings.load()
136
#if ENABLED(PIDTEMP)
137
  #if ENABLED(PID_PARAMS_PER_HOTEND) && HOTENDS > 1
138
    float Temperature::Kp[HOTENDS], Temperature::Ki[HOTENDS], Temperature::Kd[HOTENDS];
139
    #if ENABLED(PID_EXTRUSION_SCALING)
140
      float Temperature::Kc[HOTENDS];
141
    #endif
142
  #else
143
    float Temperature::Kp, Temperature::Ki, Temperature::Kd;
144
    #if ENABLED(PID_EXTRUSION_SCALING)
145
      float Temperature::Kc;
146
    #endif
147
  #endif
148
#endif
149
 
150
#if ENABLED(BABYSTEPPING)
151
  volatile int Temperature::babystepsTodo[XYZ] = { 0 };
152
#endif
153
 
154
#if WATCH_HOTENDS
155
  uint16_t Temperature::watch_target_temp[HOTENDS] = { 0 };
156
  millis_t Temperature::watch_heater_next_ms[HOTENDS] = { 0 };
157
#endif
158
 
159
#if ENABLED(PREVENT_COLD_EXTRUSION)
160
  bool Temperature::allow_cold_extrude = false;
161
  int16_t Temperature::extrude_min_temp = EXTRUDE_MINTEMP;
162
#endif
163
 
164
#if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
165
  uint16_t Temperature::redundant_temperature_raw = 0;
166
  float Temperature::redundant_temperature = 0.0;
167
#endif
168
 
169
volatile bool Temperature::temp_meas_ready = false;
170
 
171
#if ENABLED(PIDTEMP)
172
  float Temperature::temp_iState[HOTENDS] = { 0 },
173
        Temperature::temp_dState[HOTENDS] = { 0 },
174
        Temperature::pTerm[HOTENDS],
175
        Temperature::iTerm[HOTENDS],
176
        Temperature::dTerm[HOTENDS];
177
 
178
  #if ENABLED(PID_EXTRUSION_SCALING)
179
    float Temperature::cTerm[HOTENDS];
180
    long Temperature::last_e_position;
181
    long Temperature::lpq[LPQ_MAX_LEN];
182
    int Temperature::lpq_ptr = 0;
183
  #endif
184
 
185
  float Temperature::pid_error[HOTENDS];
186
  bool Temperature::pid_reset[HOTENDS];
187
#endif
188
 
189
uint16_t Temperature::raw_temp_value[MAX_EXTRUDERS] = { 0 };
190
 
191
// Init min and max temp with extreme values to prevent false errors during startup
192
int16_t Temperature::minttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP, HEATER_3_RAW_LO_TEMP, HEATER_4_RAW_LO_TEMP),
193
        Temperature::maxttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP, HEATER_3_RAW_HI_TEMP, HEATER_4_RAW_HI_TEMP),
194
        Temperature::minttemp[HOTENDS] = { 0 },
195
        Temperature::maxttemp[HOTENDS] = ARRAY_BY_HOTENDS1(16383);
196
 
197
#ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
198
  uint8_t Temperature::consecutive_low_temperature_error[HOTENDS] = { 0 };
199
#endif
200
 
201
#ifdef MILLISECONDS_PREHEAT_TIME
202
  millis_t Temperature::preheat_end_time[HOTENDS] = { 0 };
203
#endif
204
 
205
#if ENABLED(FILAMENT_WIDTH_SENSOR)
206
  int8_t Temperature::meas_shift_index;  // Index of a delayed sample in buffer
207
#endif
208
 
209
#if HAS_AUTO_FAN
210
  millis_t Temperature::next_auto_fan_check_ms = 0;
211
#endif
212
 
213
uint8_t Temperature::soft_pwm_amount[HOTENDS];
214
 
215
#if ENABLED(FAN_SOFT_PWM)
216
  uint8_t Temperature::soft_pwm_amount_fan[FAN_COUNT],
217
          Temperature::soft_pwm_count_fan[FAN_COUNT];
218
#endif
219
 
220
#if ENABLED(FILAMENT_WIDTH_SENSOR)
221
  uint16_t Temperature::current_raw_filwidth = 0; // Measured filament diameter - one extruder only
222
#endif
223
 
224
#if ENABLED(PROBING_HEATERS_OFF)
225
  bool Temperature::paused;
226
#endif
227
 
228
#if HEATER_IDLE_HANDLER
229
  millis_t Temperature::heater_idle_timeout_ms[HOTENDS] = { 0 };
230
  bool Temperature::heater_idle_timeout_exceeded[HOTENDS] = { false };
231
#endif
232
 
233
#if ENABLED(ADC_KEYPAD)
234
  uint32_t Temperature::current_ADCKey_raw = 0;
235
  uint8_t Temperature::ADCKey_count = 0;
236
#endif
237
 
238
#if ENABLED(PID_EXTRUSION_SCALING)
239
  int16_t Temperature::lpq_len; // Initialized in configuration_store
240
#endif
241
 
242
#if HAS_PID_HEATING
243
 
244
  /**
245
   * PID Autotuning (M303)
246
   *
247
   * Alternately heat and cool the nozzle, observing its behavior to
248
   * determine the best PID values to achieve a stable temperature.
249
   */
250
  void Temperature::pid_autotune(const float &target, const int8_t hotend, const int8_t ncycles, const bool set_result/*=false*/) {
251
    float current = 0.0;
252
    int cycles = 0;
253
    bool heating = true;
254
 
255
    millis_t next_temp_ms = millis(), t1 = next_temp_ms, t2 = next_temp_ms;
256
    long t_high = 0, t_low = 0;
257
 
258
    long bias, d;
259
    float Ku, Tu,
260
          workKp = 0, workKi = 0, workKd = 0,
261
          max = 0, min = 10000;
262
 
263
    #if HAS_PID_FOR_BOTH
264
      #define GHV(B,H) (hotend < 0 ? (B) : (H))
265
      #define SHV(S,B,H) if (hotend < 0) S##_bed = B; else S [hotend] = H;
266
    #elif ENABLED(PIDTEMPBED)
267
      #define GHV(B,H) B
268
      #define SHV(S,B,H) (S##_bed = B)
269
    #else
270
      #define GHV(B,H) H
271
      #define SHV(S,B,H) (S [hotend] = H)
272
    #endif
273
 
274
    #if WATCH_THE_BED || WATCH_HOTENDS
275
      #define HAS_TP_BED (ENABLED(THERMAL_PROTECTION_BED) && ENABLED(PIDTEMPBED))
276
      #if HAS_TP_BED && ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(PIDTEMP)
277
        #define GTV(B,H) (hotend < 0 ? (B) : (H))
278
      #elif HAS_TP_BED
279
        #define GTV(B,H) (B)
280
      #else
281
        #define GTV(B,H) (H)
282
      #endif
283
      const uint16_t watch_temp_period = GTV(WATCH_BED_TEMP_PERIOD, WATCH_TEMP_PERIOD);
284
      const uint8_t watch_temp_increase = GTV(WATCH_BED_TEMP_INCREASE, WATCH_TEMP_INCREASE);
285
      const float watch_temp_target = target - float(watch_temp_increase + GTV(TEMP_BED_HYSTERESIS, TEMP_HYSTERESIS) + 1);
286
      millis_t temp_change_ms = next_temp_ms + watch_temp_period * 1000UL;
287
      float next_watch_temp = 0.0;
288
      bool heated = false;
289
    #endif
290
 
291
    #if HAS_AUTO_FAN
292
      next_auto_fan_check_ms = next_temp_ms + 2500UL;
293
    #endif
294
 
295
    #if ENABLED(PIDTEMP)
296
      #define _TOP_HOTEND HOTENDS - 1
297
    #else
298
      #define _TOP_HOTEND -1
299
    #endif
300
    #if ENABLED(PIDTEMPBED)
301
      #define _BOT_HOTEND -1
302
    #else
303
      #define _BOT_HOTEND 0
304
    #endif
305
 
306
    if (!WITHIN(hotend, _BOT_HOTEND, _TOP_HOTEND)) {
307
      SERIAL_ECHOLNPGM(MSG_PID_BAD_EXTRUDER_NUM);
308
      return;
309
    }
310
 
311
    if (target > GHV(BED_MAXTEMP, maxttemp[hotend]) - 15) {
312
      SERIAL_ECHOLNPGM(MSG_PID_TEMP_TOO_HIGH);
313
      return;
314
    }
315
 
316
    SERIAL_ECHOLNPGM(MSG_PID_AUTOTUNE_START);
317
 
318
    disable_all_heaters(); // switch off all heaters.
319
 
320
    SHV(soft_pwm_amount, bias = d = (MAX_BED_POWER) >> 1, bias = d = (PID_MAX) >> 1);
321
 
322
    wait_for_heatup = true; // Can be interrupted with M108
323
 
324
    // PID Tuning loop
325
    while (wait_for_heatup) {
326
 
327
      const millis_t ms = millis();
328
 
329
      if (temp_meas_ready) { // temp sample ready
330
        calculate_celsius_temperatures();
331
 
332
        // Get the current temperature and constrain it
333
        current = GHV(current_temperature_bed, current_temperature[hotend]);
334
        NOLESS(max, current);
335
        NOMORE(min, current);
336
 
337
        #if HAS_AUTO_FAN
338
          if (ELAPSED(ms, next_auto_fan_check_ms)) {
339
            check_extruder_auto_fans();
340
            next_auto_fan_check_ms = ms + 2500UL;
341
          }
342
        #endif
343
 
344
        if (heating && current > target) {
345
          if (ELAPSED(ms, t2 + 5000UL)) {
346
            heating = false;
347
            SHV(soft_pwm_amount, (bias - d) >> 1, (bias - d) >> 1);
348
            t1 = ms;
349
            t_high = t1 - t2;
350
            max = target;
351
          }
352
        }
353
 
354
        if (!heating && current < target) {
355
          if (ELAPSED(ms, t1 + 5000UL)) {
356
            heating = true;
357
            t2 = ms;
358
            t_low = t2 - t1;
359
            if (cycles > 0) {
360
              const long max_pow = GHV(MAX_BED_POWER, PID_MAX);
361
              bias += (d * (t_high - t_low)) / (t_low + t_high);
362
              bias = constrain(bias, 20, max_pow - 20);
363
              d = (bias > max_pow >> 1) ? max_pow - 1 - bias : bias;
364
 
365
              SERIAL_PROTOCOLPAIR(MSG_BIAS, bias);
366
              SERIAL_PROTOCOLPAIR(MSG_D, d);
367
              SERIAL_PROTOCOLPAIR(MSG_T_MIN, min);
368
              SERIAL_PROTOCOLPAIR(MSG_T_MAX, max);
369
              if (cycles > 2) {
370
                Ku = (4.0f * d) / (M_PI * (max - min) * 0.5f);
371
                Tu = ((float)(t_low + t_high) * 0.001f);
372
                SERIAL_PROTOCOLPAIR(MSG_KU, Ku);
373
                SERIAL_PROTOCOLPAIR(MSG_TU, Tu);
374
                workKp = 0.6f * Ku;
375
                workKi = 2 * workKp / Tu;
376
                workKd = workKp * Tu * 0.125f;
377
                SERIAL_PROTOCOLLNPGM("\n" MSG_CLASSIC_PID);
378
                SERIAL_PROTOCOLPAIR(MSG_KP, workKp);
379
                SERIAL_PROTOCOLPAIR(MSG_KI, workKi);
380
                SERIAL_PROTOCOLLNPAIR(MSG_KD, workKd);
381
                /**
382
                workKp = 0.33*Ku;
383
                workKi = workKp/Tu;
384
                workKd = workKp*Tu/3;
385
                SERIAL_PROTOCOLLNPGM(" Some overshoot");
386
                SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
387
                SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
388
                SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
389
                workKp = 0.2*Ku;
390
                workKi = 2*workKp/Tu;
391
                workKd = workKp*Tu/3;
392
                SERIAL_PROTOCOLLNPGM(" No overshoot");
393
                SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
394
                SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
395
                SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
396
                */
397
              }
398
            }
399
            SHV(soft_pwm_amount, (bias + d) >> 1, (bias + d) >> 1);
400
            cycles++;
401
            min = target;
402
          }
403
        }
404
      }
405
 
406
      // Did the temperature overshoot very far?
407
      #ifndef MAX_OVERSHOOT_PID_AUTOTUNE
408
        #define MAX_OVERSHOOT_PID_AUTOTUNE 20
409
      #endif
410
      if (current > target + MAX_OVERSHOOT_PID_AUTOTUNE) {
411
        SERIAL_PROTOCOLLNPGM(MSG_PID_TEMP_TOO_HIGH);
412
        break;
413
      }
414
 
415
      // Report heater states every 2 seconds
416
      if (ELAPSED(ms, next_temp_ms)) {
417
        #if HAS_TEMP_SENSOR
418
          print_heaterstates();
419
          SERIAL_EOL();
420
        #endif
421
        next_temp_ms = ms + 2000UL;
422
 
423
        // Make sure heating is actually working
424
        #if WATCH_THE_BED || WATCH_HOTENDS
425
          if (
426
            #if WATCH_THE_BED && WATCH_HOTENDS
427
              true
428
            #elif WATCH_HOTENDS
429
              hotend >= 0
430
            #else
431
              hotend < 0
432
            #endif
433
          ) {
434
            if (!heated) {                                          // If not yet reached target...
435
              if (current > next_watch_temp) {                      // Over the watch temp?
436
                next_watch_temp = current + watch_temp_increase;    // - set the next temp to watch for
437
                temp_change_ms = ms + watch_temp_period * 1000UL;   // - move the expiration timer up
438
                if (current > watch_temp_target) heated = true;     // - Flag if target temperature reached
439
              }
440
              else if (ELAPSED(ms, temp_change_ms))                 // Watch timer expired
441
                _temp_error(hotend, PSTR(MSG_T_HEATING_FAILED), TEMP_ERR_PSTR(MSG_HEATING_FAILED_LCD, hotend));
442
            }
443
            else if (current < target - (MAX_OVERSHOOT_PID_AUTOTUNE)) // Heated, then temperature fell too far?
444
              _temp_error(hotend, PSTR(MSG_T_THERMAL_RUNAWAY), TEMP_ERR_PSTR(MSG_THERMAL_RUNAWAY, hotend));
445
          }
446
        #endif
447
      } // every 2 seconds
448
 
449
      // Timeout after MAX_CYCLE_TIME_PID_AUTOTUNE minutes since the last undershoot/overshoot cycle
450
      #ifndef MAX_CYCLE_TIME_PID_AUTOTUNE
451
        #define MAX_CYCLE_TIME_PID_AUTOTUNE 20L
452
      #endif
453
      if (((ms - t1) + (ms - t2)) > (MAX_CYCLE_TIME_PID_AUTOTUNE * 60L * 1000L)) {
454
        SERIAL_PROTOCOLLNPGM(MSG_PID_TIMEOUT);
455
        break;
456
      }
457
 
458
      if (cycles > ncycles) {
459
        SERIAL_PROTOCOLLNPGM(MSG_PID_AUTOTUNE_FINISHED);
460
 
461
        #if HAS_PID_FOR_BOTH
462
          const char* estring = GHV("bed", "");
463
          SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kp ", workKp); SERIAL_EOL();
464
          SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Ki ", workKi); SERIAL_EOL();
465
          SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kd ", workKd); SERIAL_EOL();
466
        #elif ENABLED(PIDTEMP)
467
          SERIAL_PROTOCOLPAIR("#define DEFAULT_Kp ", workKp); SERIAL_EOL();
468
          SERIAL_PROTOCOLPAIR("#define DEFAULT_Ki ", workKi); SERIAL_EOL();
469
          SERIAL_PROTOCOLPAIR("#define DEFAULT_Kd ", workKd); SERIAL_EOL();
470
        #else
471
          SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKp ", workKp); SERIAL_EOL();
472
          SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKi ", workKi); SERIAL_EOL();
473
          SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKd ", workKd); SERIAL_EOL();
474
        #endif
475
 
476
        #define _SET_BED_PID() do { \
477
          bedKp = workKp; \
478
          bedKi = scalePID_i(workKi); \
479
          bedKd = scalePID_d(workKd); \
480
        }while(0)
481
 
482
        #define _SET_EXTRUDER_PID() do { \
483
          PID_PARAM(Kp, hotend) = workKp; \
484
          PID_PARAM(Ki, hotend) = scalePID_i(workKi); \
485
          PID_PARAM(Kd, hotend) = scalePID_d(workKd); \
486
          update_pid(); }while(0)
487
 
488
        // Use the result? (As with "M303 U1")
489
        if (set_result) {
490
          #if HAS_PID_FOR_BOTH
491
            if (hotend < 0)
492
              _SET_BED_PID();
493
            else
494
              _SET_EXTRUDER_PID();
495
          #elif ENABLED(PIDTEMP)
496
            _SET_EXTRUDER_PID();
497
          #else
498
            _SET_BED_PID();
499
          #endif
500
        }
501
        return;
502
      }
503
      lcd_update();
504
    }
505
    disable_all_heaters();
506
  }
507
 
508
#endif // HAS_PID_HEATING
509
 
510
/**
511
 * Class and Instance Methods
512
 */
513
 
514
Temperature::Temperature() { }
515
 
516
int Temperature::getHeaterPower(const int heater) {
517
  return (
518
    #if HAS_HEATED_BED
519
      heater < 0 ? soft_pwm_amount_bed :
520
    #endif
521
    soft_pwm_amount[heater]
522
  );
523
}
524
 
525
#if HAS_AUTO_FAN
526
 
527
  void Temperature::check_extruder_auto_fans() {
528
    static const pin_t fanPin[] PROGMEM = { E0_AUTO_FAN_PIN, E1_AUTO_FAN_PIN, E2_AUTO_FAN_PIN, E3_AUTO_FAN_PIN, E4_AUTO_FAN_PIN, CHAMBER_AUTO_FAN_PIN };
529
    static const uint8_t fanBit[] PROGMEM = {
530
                    0,
531
      AUTO_1_IS_0 ? 0 :               1,
532
      AUTO_2_IS_0 ? 0 : AUTO_2_IS_1 ? 1 :               2,
533
      AUTO_3_IS_0 ? 0 : AUTO_3_IS_1 ? 1 : AUTO_3_IS_2 ? 2 :               3,
534
      AUTO_4_IS_0 ? 0 : AUTO_4_IS_1 ? 1 : AUTO_4_IS_2 ? 2 : AUTO_4_IS_3 ? 3 : 4,
535
      AUTO_CHAMBER_IS_0 ? 0 : AUTO_CHAMBER_IS_1 ? 1 : AUTO_CHAMBER_IS_2 ? 2 : AUTO_CHAMBER_IS_3 ? 3 : AUTO_CHAMBER_IS_4 ? 4 : 5
536
    };
537
    uint8_t fanState = 0;
538
 
539
    HOTEND_LOOP()
540
      if (current_temperature[e] > EXTRUDER_AUTO_FAN_TEMPERATURE)
541
        SBI(fanState, pgm_read_byte(&fanBit[e]));
542
 
543
    #if HAS_TEMP_CHAMBER
544
      if (current_temperature_chamber > EXTRUDER_AUTO_FAN_TEMPERATURE)
545
        SBI(fanState, pgm_read_byte(&fanBit[5]));
546
    #endif
547
 
548
    uint8_t fanDone = 0;
549
    for (uint8_t f = 0; f < COUNT(fanPin); f++) {
550
      const pin_t pin =
551
        #ifdef ARDUINO
552
          pgm_read_byte(&fanPin[f])
553
        #else
554
          fanPin[f]
555
        #endif
556
      ;
557
      const uint8_t bit = pgm_read_byte(&fanBit[f]);
558
      if (pin >= 0 && !TEST(fanDone, bit)) {
559
        uint8_t newFanSpeed = TEST(fanState, bit) ? EXTRUDER_AUTO_FAN_SPEED : 0;
560
        #if ENABLED(AUTO_POWER_E_FANS)
561
          autofan_speed[f] = newFanSpeed;
562
        #endif
563
        // this idiom allows both digital and PWM fan outputs (see M42 handling).
564
        digitalWrite(pin, newFanSpeed);
565
        analogWrite(pin, newFanSpeed);
566
        SBI(fanDone, bit);
567
      }
568
    }
569
  }
570
 
571
#endif // HAS_AUTO_FAN
572
 
573
//
574
// Temperature Error Handlers
575
//
576
void Temperature::_temp_error(const int8_t e, const char * const serial_msg, const char * const lcd_msg) {
577
  if (IsRunning()) {
578
    SERIAL_ERROR_START();
579
    serialprintPGM(serial_msg);
580
    SERIAL_ERRORPGM(MSG_STOPPED_HEATER);
581
    if (e >= 0) SERIAL_ERRORLN((int)e); else SERIAL_ERRORLNPGM(MSG_HEATER_BED);
582
  }
583
  #if DISABLED(BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE)
584
    static bool killed = false;
585
    if (!killed) {
586
      Running = false;
587
      killed = true;
588
      kill(lcd_msg);
589
    }
590
    else
591
      disable_all_heaters(); // paranoia
592
  #endif
593
}
594
 
595
void Temperature::max_temp_error(const int8_t e) {
596
  _temp_error(e, PSTR(MSG_T_MAXTEMP), TEMP_ERR_PSTR(MSG_ERR_MAXTEMP, e));
597
}
598
 
599
void Temperature::min_temp_error(const int8_t e) {
600
  _temp_error(e, PSTR(MSG_T_MINTEMP), TEMP_ERR_PSTR(MSG_ERR_MINTEMP, e));
601
}
602
 
603
float Temperature::get_pid_output(const int8_t e) {
604
  #if HOTENDS == 1
605
    UNUSED(e);
606
    #define _HOTEND_TEST     true
607
  #else
608
    #define _HOTEND_TEST     e == active_extruder
609
  #endif
610
  float pid_output;
611
  #if ENABLED(PIDTEMP)
612
    #if DISABLED(PID_OPENLOOP)
613
      pid_error[HOTEND_INDEX] = target_temperature[HOTEND_INDEX] - current_temperature[HOTEND_INDEX];
614
      dTerm[HOTEND_INDEX] = PID_K2 * PID_PARAM(Kd, HOTEND_INDEX) * (current_temperature[HOTEND_INDEX] - temp_dState[HOTEND_INDEX]) + float(PID_K1) * dTerm[HOTEND_INDEX];
615
      temp_dState[HOTEND_INDEX] = current_temperature[HOTEND_INDEX];
616
 
617
      if (target_temperature[HOTEND_INDEX] == 0
618
        || pid_error[HOTEND_INDEX] < -(PID_FUNCTIONAL_RANGE)
619
        #if HEATER_IDLE_HANDLER
620
          || heater_idle_timeout_exceeded[HOTEND_INDEX]
621
        #endif
622
      ) {
623
        pid_output = 0;
624
        pid_reset[HOTEND_INDEX] = true;
625
      }
626
      else if (pid_error[HOTEND_INDEX] > PID_FUNCTIONAL_RANGE) {
627
        pid_output = BANG_MAX;
628
        pid_reset[HOTEND_INDEX] = true;
629
      }
630
      else {
631
        if (pid_reset[HOTEND_INDEX]) {
632
          temp_iState[HOTEND_INDEX] = 0.0;
633
          pid_reset[HOTEND_INDEX] = false;
634
        }
635
        pTerm[HOTEND_INDEX] = PID_PARAM(Kp, HOTEND_INDEX) * pid_error[HOTEND_INDEX];
636
        temp_iState[HOTEND_INDEX] += pid_error[HOTEND_INDEX];
637
        iTerm[HOTEND_INDEX] = PID_PARAM(Ki, HOTEND_INDEX) * temp_iState[HOTEND_INDEX];
638
 
639
        pid_output = pTerm[HOTEND_INDEX] + iTerm[HOTEND_INDEX] - dTerm[HOTEND_INDEX];
640
 
641
        #if ENABLED(PID_EXTRUSION_SCALING)
642
          cTerm[HOTEND_INDEX] = 0;
643
          if (_HOTEND_TEST) {
644
            const long e_position = stepper.position(E_AXIS);
645
            if (e_position > last_e_position) {
646
              lpq[lpq_ptr] = e_position - last_e_position;
647
              last_e_position = e_position;
648
            }
649
            else
650
              lpq[lpq_ptr] = 0;
651
 
652
            if (++lpq_ptr >= lpq_len) lpq_ptr = 0;
653
            cTerm[HOTEND_INDEX] = (lpq[lpq_ptr] * planner.steps_to_mm[E_AXIS]) * PID_PARAM(Kc, HOTEND_INDEX);
654
            pid_output += cTerm[HOTEND_INDEX];
655
          }
656
        #endif // PID_EXTRUSION_SCALING
657
 
658
        if (pid_output > PID_MAX) {
659
          if (pid_error[HOTEND_INDEX] > 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
660
          pid_output = PID_MAX;
661
        }
662
        else if (pid_output < 0) {
663
          if (pid_error[HOTEND_INDEX] < 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
664
          pid_output = 0;
665
        }
666
      }
667
    #else
668
      pid_output = constrain(target_temperature[HOTEND_INDEX], 0, PID_MAX);
669
    #endif // PID_OPENLOOP
670
 
671
    #if ENABLED(PID_DEBUG)
672
      SERIAL_ECHO_START();
673
      SERIAL_ECHOPAIR(MSG_PID_DEBUG, HOTEND_INDEX);
674
      SERIAL_ECHOPAIR(MSG_PID_DEBUG_INPUT, current_temperature[HOTEND_INDEX]);
675
      SERIAL_ECHOPAIR(MSG_PID_DEBUG_OUTPUT, pid_output);
676
      SERIAL_ECHOPAIR(MSG_PID_DEBUG_PTERM, pTerm[HOTEND_INDEX]);
677
      SERIAL_ECHOPAIR(MSG_PID_DEBUG_ITERM, iTerm[HOTEND_INDEX]);
678
      SERIAL_ECHOPAIR(MSG_PID_DEBUG_DTERM, dTerm[HOTEND_INDEX]);
679
      #if ENABLED(PID_EXTRUSION_SCALING)
680
        SERIAL_ECHOPAIR(MSG_PID_DEBUG_CTERM, cTerm[HOTEND_INDEX]);
681
      #endif
682
      SERIAL_EOL();
683
    #endif // PID_DEBUG
684
 
685
  #else /* PID off */
686
    #if HEATER_IDLE_HANDLER
687
      if (heater_idle_timeout_exceeded[HOTEND_INDEX])
688
        pid_output = 0;
689
      else
690
    #endif
691
    pid_output = (current_temperature[HOTEND_INDEX] < target_temperature[HOTEND_INDEX]) ? PID_MAX : 0;
692
  #endif
693
 
694
  return pid_output;
695
}
696
 
697
#if ENABLED(PIDTEMPBED)
698
  float Temperature::get_pid_output_bed() {
699
    float pid_output;
700
    #if DISABLED(PID_OPENLOOP)
701
      pid_error_bed = target_temperature_bed - current_temperature_bed;
702
      pTerm_bed = bedKp * pid_error_bed;
703
      temp_iState_bed += pid_error_bed;
704
      iTerm_bed = bedKi * temp_iState_bed;
705
 
706
      dTerm_bed = PID_K2 * bedKd * (current_temperature_bed - temp_dState_bed) + PID_K1 * dTerm_bed;
707
      temp_dState_bed = current_temperature_bed;
708
 
709
      pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
710
      if (pid_output > MAX_BED_POWER) {
711
        if (pid_error_bed > 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
712
        pid_output = MAX_BED_POWER;
713
      }
714
      else if (pid_output < 0) {
715
        if (pid_error_bed < 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
716
        pid_output = 0;
717
      }
718
    #else
719
      pid_output = constrain(target_temperature_bed, 0, MAX_BED_POWER);
720
    #endif // PID_OPENLOOP
721
 
722
    #if ENABLED(PID_BED_DEBUG)
723
      SERIAL_ECHO_START();
724
      SERIAL_ECHOPGM(" PID_BED_DEBUG ");
725
      SERIAL_ECHOPGM(": Input ");
726
      SERIAL_ECHO(current_temperature_bed);
727
      SERIAL_ECHOPGM(" Output ");
728
      SERIAL_ECHO(pid_output);
729
      SERIAL_ECHOPGM(" pTerm ");
730
      SERIAL_ECHO(pTerm_bed);
731
      SERIAL_ECHOPGM(" iTerm ");
732
      SERIAL_ECHO(iTerm_bed);
733
      SERIAL_ECHOPGM(" dTerm ");
734
      SERIAL_ECHOLN(dTerm_bed);
735
    #endif // PID_BED_DEBUG
736
 
737
    return pid_output;
738
  }
739
#endif // PIDTEMPBED
740
 
741
/**
742
 * Manage heating activities for extruder hot-ends and a heated bed
743
 *  - Acquire updated temperature readings
744
 *    - Also resets the watchdog timer
745
 *  - Invoke thermal runaway protection
746
 *  - Manage extruder auto-fan
747
 *  - Apply filament width to the extrusion rate (may move)
748
 *  - Update the heated bed PID output value
749
 */
750
void Temperature::manage_heater() {
751
 
752
  #if ENABLED(PROBING_HEATERS_OFF) && ENABLED(BED_LIMIT_SWITCHING)
753
    static bool last_pause_state;
754
  #endif
755
 
756
  #if ENABLED(EMERGENCY_PARSER)
757
    if (emergency_parser.killed_by_M112) kill(PSTR(MSG_KILLED));
758
  #endif
759
 
760
  if (!temp_meas_ready) return;
761
 
762
  calculate_celsius_temperatures(); // also resets the watchdog
763
 
764
  #if ENABLED(HEATER_0_USES_MAX6675)
765
    if (current_temperature[0] > MIN(HEATER_0_MAXTEMP, MAX6675_TMAX - 1.0)) max_temp_error(0);
766
    if (current_temperature[0] < MAX(HEATER_0_MINTEMP, MAX6675_TMIN + .01)) min_temp_error(0);
767
  #endif
768
 
769
  #if WATCH_HOTENDS || WATCH_THE_BED || DISABLED(PIDTEMPBED) || HAS_AUTO_FAN || HEATER_IDLE_HANDLER
770
    millis_t ms = millis();
771
  #endif
772
 
773
  HOTEND_LOOP() {
774
 
775
    #if HEATER_IDLE_HANDLER
776
      if (!heater_idle_timeout_exceeded[e] && heater_idle_timeout_ms[e] && ELAPSED(ms, heater_idle_timeout_ms[e]))
777
        heater_idle_timeout_exceeded[e] = true;
778
    #endif
779
 
780
    #if ENABLED(THERMAL_PROTECTION_HOTENDS)
781
      // Check for thermal runaway
782
      thermal_runaway_protection(&thermal_runaway_state_machine[e], &thermal_runaway_timer[e], current_temperature[e], target_temperature[e], e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS);
783
    #endif
784
 
785
    soft_pwm_amount[e] = (current_temperature[e] > minttemp[e] || is_preheating(e)) && current_temperature[e] < maxttemp[e] ? (int)get_pid_output(e) >> 1 : 0;
786
 
787
    #if WATCH_HOTENDS
788
      // Make sure temperature is increasing
789
      if (watch_heater_next_ms[e] && ELAPSED(ms, watch_heater_next_ms[e])) { // Time to check this extruder?
790
        if (degHotend(e) < watch_target_temp[e])                             // Failed to increase enough?
791
          _temp_error(e, PSTR(MSG_T_HEATING_FAILED), TEMP_ERR_PSTR(MSG_HEATING_FAILED_LCD, e));
792
        else                                                                 // Start again if the target is still far off
793
          start_watching_heater(e);
794
      }
795
    #endif
796
 
797
    #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
798
      // Make sure measured temperatures are close together
799
      if (ABS(current_temperature[0] - redundant_temperature) > MAX_REDUNDANT_TEMP_SENSOR_DIFF)
800
        _temp_error(0, PSTR(MSG_REDUNDANCY), PSTR(MSG_ERR_REDUNDANT_TEMP));
801
    #endif
802
 
803
  } // HOTEND_LOOP
804
 
805
  #if HAS_AUTO_FAN
806
    if (ELAPSED(ms, next_auto_fan_check_ms)) { // only need to check fan state very infrequently
807
      check_extruder_auto_fans();
808
      next_auto_fan_check_ms = ms + 2500UL;
809
    }
810
  #endif
811
 
812
  #if ENABLED(FILAMENT_WIDTH_SENSOR)
813
    /**
814
     * Filament Width Sensor dynamically sets the volumetric multiplier
815
     * based on a delayed measurement of the filament diameter.
816
     */
817
    if (filament_sensor) {
818
      meas_shift_index = filwidth_delay_index[0] - meas_delay_cm;
819
      if (meas_shift_index < 0) meas_shift_index += MAX_MEASUREMENT_DELAY + 1;  //loop around buffer if needed
820
      meas_shift_index = constrain(meas_shift_index, 0, MAX_MEASUREMENT_DELAY);
821
      planner.calculate_volumetric_for_width_sensor(measurement_delay[meas_shift_index]);
822
    }
823
  #endif // FILAMENT_WIDTH_SENSOR
824
 
825
  #if HAS_HEATED_BED
826
 
827
    #if WATCH_THE_BED
828
      // Make sure temperature is increasing
829
      if (watch_bed_next_ms && ELAPSED(ms, watch_bed_next_ms)) {        // Time to check the bed?
830
        if (degBed() < watch_target_bed_temp)                           // Failed to increase enough?
831
          _temp_error(-1, PSTR(MSG_T_HEATING_FAILED), TEMP_ERR_PSTR(MSG_HEATING_FAILED_LCD, -1));
832
        else                                                            // Start again if the target is still far off
833
          start_watching_bed();
834
      }
835
    #endif // WATCH_THE_BED
836
 
837
    #if DISABLED(PIDTEMPBED)
838
      if (PENDING(ms, next_bed_check_ms)
839
        #if ENABLED(PROBING_HEATERS_OFF) && ENABLED(BED_LIMIT_SWITCHING)
840
          && paused == last_pause_state
841
        #endif
842
      ) return;
843
      next_bed_check_ms = ms + BED_CHECK_INTERVAL;
844
      #if ENABLED(PROBING_HEATERS_OFF) && ENABLED(BED_LIMIT_SWITCHING)
845
        last_pause_state = paused;
846
      #endif
847
    #endif
848
 
849
    #if HEATER_IDLE_HANDLER
850
      if (!bed_idle_timeout_exceeded && bed_idle_timeout_ms && ELAPSED(ms, bed_idle_timeout_ms))
851
        bed_idle_timeout_exceeded = true;
852
    #endif
853
 
854
    #if HAS_THERMALLY_PROTECTED_BED
855
      thermal_runaway_protection(&thermal_runaway_bed_state_machine, &thermal_runaway_bed_timer, current_temperature_bed, target_temperature_bed, -1, THERMAL_PROTECTION_BED_PERIOD, THERMAL_PROTECTION_BED_HYSTERESIS);
856
    #endif
857
 
858
    #if HEATER_IDLE_HANDLER
859
      if (bed_idle_timeout_exceeded) {
860
        soft_pwm_amount_bed = 0;
861
        #if DISABLED(PIDTEMPBED)
862
          WRITE_HEATER_BED(LOW);
863
        #endif
864
      }
865
      else
866
    #endif
867
    {
868
      #if ENABLED(PIDTEMPBED)
869
        soft_pwm_amount_bed = WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP) ? (int)get_pid_output_bed() >> 1 : 0;
870
      #else
871
        // Check if temperature is within the correct band
872
        if (WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP)) {
873
          #if ENABLED(BED_LIMIT_SWITCHING)
874
            if (current_temperature_bed >= target_temperature_bed + BED_HYSTERESIS)
875
              soft_pwm_amount_bed = 0;
876
            else if (current_temperature_bed <= target_temperature_bed - (BED_HYSTERESIS))
877
              soft_pwm_amount_bed = MAX_BED_POWER >> 1;
878
          #else // !PIDTEMPBED && !BED_LIMIT_SWITCHING
879
            soft_pwm_amount_bed = current_temperature_bed < target_temperature_bed ? MAX_BED_POWER >> 1 : 0;
880
          #endif
881
        }
882
        else {
883
          soft_pwm_amount_bed = 0;
884
          WRITE_HEATER_BED(LOW);
885
        }
886
      #endif
887
    }
888
  #endif // HAS_HEATED_BED
889
}
890
 
891
#define TEMP_AD595(RAW)  ((RAW) * 5.0 * 100.0 / 1024.0 / (OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET)
892
#define TEMP_AD8495(RAW) ((RAW) * 6.6 * 100.0 / 1024.0 / (OVERSAMPLENR) * (TEMP_SENSOR_AD8495_GAIN) + TEMP_SENSOR_AD8495_OFFSET)
893
 
894
/**
895
 * Bisect search for the range of the 'raw' value, then interpolate
896
 * proportionally between the under and over values.
897
 */
898
#define SCAN_THERMISTOR_TABLE(TBL,LEN) do{                             \
899
  uint8_t l = 0, r = LEN, m;                                           \
900
  for (;;) {                                                           \
901
    m = (l + r) >> 1;                                                  \
902
    if (m == l || m == r) return (short)pgm_read_word(&TBL[LEN-1][1]); \
903
    short v00 = pgm_read_word(&TBL[m-1][0]),                           \
904
          v10 = pgm_read_word(&TBL[m-0][0]);                           \
905
         if (raw < v00) r = m;                                         \
906
    else if (raw > v10) l = m;                                         \
907
    else {                                                             \
908
      const short v01 = (short)pgm_read_word(&TBL[m-1][1]),            \
909
                  v11 = (short)pgm_read_word(&TBL[m-0][1]);            \
910
      return v01 + (raw - v00) * float(v11 - v01) / float(v10 - v00);  \
911
    }                                                                  \
912
  }                                                                    \
913
}while(0)
914
 
915
// Derived from RepRap FiveD extruder::getTemperature()
916
// For hot end temperature measurement.
917
float Temperature::analog_to_celsius_hotend(const int raw, const uint8_t e) {
918
  #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
919
    if (e > HOTENDS)
920
  #else
921
    if (e >= HOTENDS)
922
  #endif
923
    {
924
      SERIAL_ERROR_START();
925
      SERIAL_ERROR((int)e);
926
      SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER_NUM);
927
      kill(PSTR(MSG_KILLED));
928
      return 0.0;
929
    }
930
 
931
  switch (e) {
932
    case 0:
933
      #if ENABLED(HEATER_0_USES_MAX6675)
934
        return raw * 0.25;
935
      #elif ENABLED(HEATER_0_USES_AD595)
936
        return TEMP_AD595(raw);
937
      #elif ENABLED(HEATER_0_USES_AD8495)
938
        return TEMP_AD8495(raw);
939
      #else
940
        break;
941
      #endif
942
    case 1:
943
      #if ENABLED(HEATER_1_USES_AD595)
944
        return TEMP_AD595(raw);
945
      #elif ENABLED(HEATER_1_USES_AD8495)
946
        return TEMP_AD8495(raw);
947
      #else
948
        break;
949
      #endif
950
    case 2:
951
      #if ENABLED(HEATER_2_USES_AD595)
952
        return TEMP_AD595(raw);
953
      #elif ENABLED(HEATER_2_USES_AD8495)
954
        return TEMP_AD8495(raw);
955
      #else
956
        break;
957
      #endif
958
    case 3:
959
      #if ENABLED(HEATER_3_USES_AD595)
960
        return TEMP_AD595(raw);
961
      #elif ENABLED(HEATER_3_USES_AD8495)
962
        return TEMP_AD8495(raw);
963
      #else
964
        break;
965
      #endif
966
    case 4:
967
      #if ENABLED(HEATER_4_USES_AD595)
968
        return TEMP_AD595(raw);
969
      #elif ENABLED(HEATER_4_USES_AD8495)
970
        return TEMP_AD8495(raw);
971
      #else
972
        break;
973
      #endif
974
    default: break;
975
  }
976
 
977
  #if HOTEND_USES_THERMISTOR
978
    // Thermistor with conversion table?
979
    const short(*tt)[][2] = (short(*)[][2])(heater_ttbl_map[e]);
980
    SCAN_THERMISTOR_TABLE((*tt), heater_ttbllen_map[e]);
981
  #endif
982
 
983
  return 0;
984
}
985
 
986
#if HAS_HEATED_BED
987
  // Derived from RepRap FiveD extruder::getTemperature()
988
  // For bed temperature measurement.
989
  float Temperature::analog_to_celsius_bed(const int raw) {
990
    #if ENABLED(HEATER_BED_USES_THERMISTOR)
991
      SCAN_THERMISTOR_TABLE(BEDTEMPTABLE, BEDTEMPTABLE_LEN);
992
    #elif ENABLED(HEATER_BED_USES_AD595)
993
      return TEMP_AD595(raw);
994
    #elif ENABLED(HEATER_BED_USES_AD8495)
995
      return TEMP_AD8495(raw);
996
    #else
997
      return 0;
998
    #endif
999
  }
1000
#endif // HAS_HEATED_BED
1001
 
1002
#if HAS_TEMP_CHAMBER
1003
  // Derived from RepRap FiveD extruder::getTemperature()
1004
  // For chamber temperature measurement.
1005
  float Temperature::analog_to_celsius_chamber(const int raw) {
1006
    #if ENABLED(HEATER_CHAMBER_USES_THERMISTOR)
1007
      SCAN_THERMISTOR_TABLE(CHAMBERTEMPTABLE, CHAMBERTEMPTABLE_LEN);
1008
    #elif ENABLED(HEATER_CHAMBER_USES_AD595)
1009
      return TEMP_AD595(raw);
1010
    #elif ENABLED(HEATER_CHAMBER_USES_AD8495)
1011
      return TEMP_AD8495(raw);
1012
    #else
1013
      return 0;
1014
    #endif
1015
  }
1016
#endif // HAS_TEMP_CHAMBER
1017
 
1018
/**
1019
 * Get the raw values into the actual temperatures.
1020
 * The raw values are created in interrupt context,
1021
 * and this function is called from normal context
1022
 * as it would block the stepper routine.
1023
 */
1024
void Temperature::calculate_celsius_temperatures() {
1025
  #if ENABLED(HEATER_0_USES_MAX6675)
1026
    current_temperature_raw[0] = read_max6675();
1027
  #endif
1028
  HOTEND_LOOP() current_temperature[e] = analog_to_celsius_hotend(current_temperature_raw[e], e);
1029
  #if HAS_HEATED_BED
1030
    current_temperature_bed = analog_to_celsius_bed(current_temperature_bed_raw);
1031
  #endif
1032
  #if HAS_TEMP_CHAMBER
1033
    current_temperature_chamber = analog_to_celsius_chamber(current_temperature_chamber_raw);
1034
  #endif
1035
  #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
1036
    redundant_temperature = analog_to_celsius_hotend(redundant_temperature_raw, 1);
1037
  #endif
1038
  #if ENABLED(FILAMENT_WIDTH_SENSOR)
1039
    filament_width_meas = analog_to_mm_fil_width();
1040
  #endif
1041
 
1042
  #if ENABLED(USE_WATCHDOG)
1043
    // Reset the watchdog after we know we have a temperature measurement.
1044
    watchdog_reset();
1045
  #endif
1046
 
1047
  temp_meas_ready = false;
1048
}
1049
 
1050
 
1051
#if ENABLED(FILAMENT_WIDTH_SENSOR)
1052
 
1053
  // Convert raw Filament Width to millimeters
1054
  float Temperature::analog_to_mm_fil_width() {
1055
    return current_raw_filwidth * 5.0f * (1.0f / 16383.0);
1056
  }
1057
 
1058
  /**
1059
   * Convert Filament Width (mm) to a simple ratio
1060
   * and reduce to an 8 bit value.
1061
   *
1062
   * A nominal width of 1.75 and measured width of 1.73
1063
   * gives (100 * 1.75 / 1.73) for a ratio of 101 and
1064
   * a return value of 1.
1065
   */
1066
  int8_t Temperature::widthFil_to_size_ratio() {
1067
    if (ABS(filament_width_nominal - filament_width_meas) <= FILWIDTH_ERROR_MARGIN)
1068
      return int(100.0f * filament_width_nominal / filament_width_meas) - 100;
1069
    return 0;
1070
  }
1071
 
1072
#endif
1073
 
1074
#if ENABLED(HEATER_0_USES_MAX6675)
1075
  #ifndef MAX6675_SCK_PIN
1076
    #define MAX6675_SCK_PIN SCK_PIN
1077
  #endif
1078
  #ifndef MAX6675_DO_PIN
1079
    #define MAX6675_DO_PIN MISO_PIN
1080
  #endif
1081
  SPI<MAX6675_DO_PIN, MOSI_PIN, MAX6675_SCK_PIN> max6675_spi;
1082
#endif
1083
 
1084
/**
1085
 * Initialize the temperature manager
1086
 * The manager is implemented by periodic calls to manage_heater()
1087
 */
1088
void Temperature::init() {
1089
 
1090
  #if MB(RUMBA) && ( \
1091
       ENABLED(HEATER_0_USES_AD595)  || ENABLED(HEATER_1_USES_AD595)  || ENABLED(HEATER_2_USES_AD595)  || ENABLED(HEATER_3_USES_AD595)  || ENABLED(HEATER_4_USES_AD595)  || ENABLED(HEATER_BED_USES_AD595)  || ENABLED(HEATER_CHAMBER_USES_AD595) \
1092
    || ENABLED(HEATER_0_USES_AD8495) || ENABLED(HEATER_1_USES_AD8495) || ENABLED(HEATER_2_USES_AD8495) || ENABLED(HEATER_3_USES_AD8495) || ENABLED(HEATER_4_USES_AD8495) || ENABLED(HEATER_BED_USES_AD8495) || ENABLED(HEATER_CHAMBER_USES_AD8495))
1093
    // Disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
1094
    MCUCR = _BV(JTD);
1095
    MCUCR = _BV(JTD);
1096
  #endif
1097
 
1098
  // Finish init of mult hotend arrays
1099
  HOTEND_LOOP() maxttemp[e] = maxttemp[0];
1100
 
1101
  #if ENABLED(PIDTEMP) && ENABLED(PID_EXTRUSION_SCALING)
1102
    last_e_position = 0;
1103
  #endif
1104
 
1105
  #if HAS_HEATER_0
1106
    SET_OUTPUT(HEATER_0_PIN);
1107
  #endif
1108
  #if HAS_HEATER_1
1109
    SET_OUTPUT(HEATER_1_PIN);
1110
  #endif
1111
  #if HAS_HEATER_2
1112
    SET_OUTPUT(HEATER_2_PIN);
1113
  #endif
1114
  #if HAS_HEATER_3
1115
    SET_OUTPUT(HEATER_3_PIN);
1116
  #endif
1117
  #if HAS_HEATER_4
1118
    SET_OUTPUT(HEATER_3_PIN);
1119
  #endif
1120
  #if HAS_HEATED_BED
1121
    SET_OUTPUT(HEATER_BED_PIN);
1122
  #endif
1123
 
1124
  #if HAS_FAN0
1125
    SET_OUTPUT(FAN_PIN);
1126
    #if ENABLED(FAST_PWM_FAN)
1127
      setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1128
    #endif
1129
  #endif
1130
 
1131
  #if HAS_FAN1
1132
    SET_OUTPUT(FAN1_PIN);
1133
    #if ENABLED(FAST_PWM_FAN)
1134
      setPwmFrequency(FAN1_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1135
    #endif
1136
  #endif
1137
 
1138
  #if HAS_FAN2
1139
    SET_OUTPUT(FAN2_PIN);
1140
    #if ENABLED(FAST_PWM_FAN)
1141
      setPwmFrequency(FAN2_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1142
    #endif
1143
  #endif
1144
 
1145
  #if ENABLED(HEATER_0_USES_MAX6675)
1146
 
1147
    OUT_WRITE(SCK_PIN, LOW);
1148
    OUT_WRITE(MOSI_PIN, HIGH);
1149
    SET_INPUT_PULLUP(MISO_PIN);
1150
 
1151
    max6675_spi.init();
1152
 
1153
    OUT_WRITE(SS_PIN, HIGH);
1154
    OUT_WRITE(MAX6675_SS, HIGH);
1155
 
1156
  #endif // HEATER_0_USES_MAX6675
1157
 
1158
  HAL_adc_init();
1159
 
1160
  #if HAS_TEMP_ADC_0
1161
    HAL_ANALOG_SELECT(TEMP_0_PIN);
1162
  #endif
1163
  #if HAS_TEMP_ADC_1
1164
    HAL_ANALOG_SELECT(TEMP_1_PIN);
1165
  #endif
1166
  #if HAS_TEMP_ADC_2
1167
    HAL_ANALOG_SELECT(TEMP_2_PIN);
1168
  #endif
1169
  #if HAS_TEMP_ADC_3
1170
    HAL_ANALOG_SELECT(TEMP_3_PIN);
1171
  #endif
1172
  #if HAS_TEMP_ADC_4
1173
    HAL_ANALOG_SELECT(TEMP_4_PIN);
1174
  #endif
1175
  #if HAS_HEATED_BED
1176
    HAL_ANALOG_SELECT(TEMP_BED_PIN);
1177
  #endif
1178
  #if HAS_TEMP_CHAMBER
1179
    HAL_ANALOG_SELECT(TEMP_CHAMBER_PIN);
1180
  #endif
1181
  #if ENABLED(FILAMENT_WIDTH_SENSOR)
1182
    HAL_ANALOG_SELECT(FILWIDTH_PIN);
1183
  #endif
1184
 
1185
  HAL_timer_start(TEMP_TIMER_NUM, TEMP_TIMER_FREQUENCY);
1186
  ENABLE_TEMPERATURE_INTERRUPT();
1187
 
1188
  #if HAS_AUTO_FAN_0
1189
    #if E0_AUTO_FAN_PIN == FAN1_PIN
1190
      SET_OUTPUT(E0_AUTO_FAN_PIN);
1191
      #if ENABLED(FAST_PWM_FAN)
1192
        setPwmFrequency(E0_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1193
      #endif
1194
    #else
1195
      SET_OUTPUT(E0_AUTO_FAN_PIN);
1196
    #endif
1197
  #endif
1198
  #if HAS_AUTO_FAN_1 && !AUTO_1_IS_0
1199
    #if E1_AUTO_FAN_PIN == FAN1_PIN
1200
      SET_OUTPUT(E1_AUTO_FAN_PIN);
1201
      #if ENABLED(FAST_PWM_FAN)
1202
        setPwmFrequency(E1_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1203
      #endif
1204
    #else
1205
      SET_OUTPUT(E1_AUTO_FAN_PIN);
1206
    #endif
1207
  #endif
1208
  #if HAS_AUTO_FAN_2 && !AUTO_2_IS_0 && !AUTO_2_IS_1
1209
    #if E2_AUTO_FAN_PIN == FAN1_PIN
1210
      SET_OUTPUT(E2_AUTO_FAN_PIN);
1211
      #if ENABLED(FAST_PWM_FAN)
1212
        setPwmFrequency(E2_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1213
      #endif
1214
    #else
1215
      SET_OUTPUT(E2_AUTO_FAN_PIN);
1216
    #endif
1217
  #endif
1218
  #if HAS_AUTO_FAN_3 && !AUTO_3_IS_0 && !AUTO_3_IS_1 && !AUTO_3_IS_2
1219
    #if E3_AUTO_FAN_PIN == FAN1_PIN
1220
      SET_OUTPUT(E3_AUTO_FAN_PIN);
1221
      #if ENABLED(FAST_PWM_FAN)
1222
        setPwmFrequency(E3_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1223
      #endif
1224
    #else
1225
      SET_OUTPUT(E3_AUTO_FAN_PIN);
1226
    #endif
1227
  #endif
1228
  #if HAS_AUTO_FAN_4 && !AUTO_4_IS_0 && !AUTO_4_IS_1 && !AUTO_4_IS_2 && !AUTO_4_IS_3
1229
    #if E4_AUTO_FAN_PIN == FAN1_PIN
1230
      SET_OUTPUT(E4_AUTO_FAN_PIN);
1231
      #if ENABLED(FAST_PWM_FAN)
1232
        setPwmFrequency(E4_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1233
      #endif
1234
    #else
1235
      SET_OUTPUT(E4_AUTO_FAN_PIN);
1236
    #endif
1237
  #endif
1238
  #if HAS_AUTO_CHAMBER_FAN && !AUTO_CHAMBER_IS_0 && !AUTO_CHAMBER_IS_1 && !AUTO_CHAMBER_IS_2 && !AUTO_CHAMBER_IS_3 && ! AUTO_CHAMBER_IS_4
1239
    #if CHAMBER_AUTO_FAN_PIN == FAN1_PIN
1240
      SET_OUTPUT(CHAMBER_AUTO_FAN_PIN);
1241
      #if ENABLED(FAST_PWM_FAN)
1242
        setPwmFrequency(CHAMBER_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
1243
      #endif
1244
    #else
1245
      SET_OUTPUT(CHAMBER_AUTO_FAN_PIN);
1246
    #endif
1247
  #endif
1248
 
1249
  // Wait for temperature measurement to settle
1250
  delay(250);
1251
 
1252
  #define TEMP_MIN_ROUTINE(NR) \
1253
    minttemp[NR] = HEATER_ ##NR## _MINTEMP; \
1254
    while (analog_to_celsius_hotend(minttemp_raw[NR], NR) < HEATER_ ##NR## _MINTEMP) { \
1255
      if (HEATER_ ##NR## _RAW_LO_TEMP < HEATER_ ##NR## _RAW_HI_TEMP) \
1256
        minttemp_raw[NR] += OVERSAMPLENR; \
1257
      else \
1258
        minttemp_raw[NR] -= OVERSAMPLENR; \
1259
    }
1260
  #define TEMP_MAX_ROUTINE(NR) \
1261
    maxttemp[NR] = HEATER_ ##NR## _MAXTEMP; \
1262
    while (analog_to_celsius_hotend(maxttemp_raw[NR], NR) > HEATER_ ##NR## _MAXTEMP) { \
1263
      if (HEATER_ ##NR## _RAW_LO_TEMP < HEATER_ ##NR## _RAW_HI_TEMP) \
1264
        maxttemp_raw[NR] -= OVERSAMPLENR; \
1265
      else \
1266
        maxttemp_raw[NR] += OVERSAMPLENR; \
1267
    }
1268
 
1269
  #ifdef HEATER_0_MINTEMP
1270
    TEMP_MIN_ROUTINE(0);
1271
  #endif
1272
  #ifdef HEATER_0_MAXTEMP
1273
    TEMP_MAX_ROUTINE(0);
1274
  #endif
1275
  #if HOTENDS > 1
1276
    #ifdef HEATER_1_MINTEMP
1277
      TEMP_MIN_ROUTINE(1);
1278
    #endif
1279
    #ifdef HEATER_1_MAXTEMP
1280
      TEMP_MAX_ROUTINE(1);
1281
    #endif
1282
    #if HOTENDS > 2
1283
      #ifdef HEATER_2_MINTEMP
1284
        TEMP_MIN_ROUTINE(2);
1285
      #endif
1286
      #ifdef HEATER_2_MAXTEMP
1287
        TEMP_MAX_ROUTINE(2);
1288
      #endif
1289
      #if HOTENDS > 3
1290
        #ifdef HEATER_3_MINTEMP
1291
          TEMP_MIN_ROUTINE(3);
1292
        #endif
1293
        #ifdef HEATER_3_MAXTEMP
1294
          TEMP_MAX_ROUTINE(3);
1295
        #endif
1296
        #if HOTENDS > 4
1297
          #ifdef HEATER_4_MINTEMP
1298
            TEMP_MIN_ROUTINE(4);
1299
          #endif
1300
          #ifdef HEATER_4_MAXTEMP
1301
            TEMP_MAX_ROUTINE(4);
1302
          #endif
1303
        #endif // HOTENDS > 4
1304
      #endif // HOTENDS > 3
1305
    #endif // HOTENDS > 2
1306
  #endif // HOTENDS > 1
1307
 
1308
  #if HAS_HEATED_BED
1309
    #ifdef BED_MINTEMP
1310
      while (analog_to_celsius_bed(bed_minttemp_raw) < BED_MINTEMP) {
1311
        #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
1312
          bed_minttemp_raw += OVERSAMPLENR;
1313
        #else
1314
          bed_minttemp_raw -= OVERSAMPLENR;
1315
        #endif
1316
      }
1317
    #endif // BED_MINTEMP
1318
    #ifdef BED_MAXTEMP
1319
      while (analog_to_celsius_bed(bed_maxttemp_raw) > BED_MAXTEMP) {
1320
        #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
1321
          bed_maxttemp_raw -= OVERSAMPLENR;
1322
        #else
1323
          bed_maxttemp_raw += OVERSAMPLENR;
1324
        #endif
1325
      }
1326
    #endif // BED_MAXTEMP
1327
  #endif // HAS_HEATED_BED
1328
 
1329
  #if ENABLED(PROBING_HEATERS_OFF)
1330
    paused = false;
1331
  #endif
1332
}
1333
 
1334
#if ENABLED(FAST_PWM_FAN)
1335
 
1336
  void Temperature::setPwmFrequency(const pin_t pin, int val) {
1337
    val &= 0x07;
1338
    switch (digitalPinToTimer(pin)) {
1339
      #ifdef TCCR0A
1340
        #if !AVR_AT90USB1286_FAMILY
1341
          case TIMER0A:
1342
        #endif
1343
        case TIMER0B:                           //_SET_CS(0, val);
1344
                                                  break;
1345
      #endif
1346
      #ifdef TCCR1A
1347
        case TIMER1A: case TIMER1B:             //_SET_CS(1, val);
1348
                                                  break;
1349
      #endif
1350
      #if defined(TCCR2) || defined(TCCR2A)
1351
        #ifdef TCCR2
1352
          case TIMER2:
1353
        #endif
1354
        #ifdef TCCR2A
1355
          case TIMER2A: case TIMER2B:
1356
        #endif
1357
                                                  _SET_CS(2, val); break;
1358
      #endif
1359
      #ifdef TCCR3A
1360
        case TIMER3A: case TIMER3B: case TIMER3C: _SET_CS(3, val); break;
1361
      #endif
1362
      #ifdef TCCR4A
1363
        case TIMER4A: case TIMER4B: case TIMER4C: _SET_CS(4, val); break;
1364
      #endif
1365
      #ifdef TCCR5A
1366
        case TIMER5A: case TIMER5B: case TIMER5C: _SET_CS(5, val); break;
1367
      #endif
1368
    }
1369
  }
1370
 
1371
#endif // FAST_PWM_FAN
1372
 
1373
#if WATCH_HOTENDS
1374
  /**
1375
   * Start Heating Sanity Check for hotends that are below
1376
   * their target temperature by a configurable margin.
1377
   * This is called when the temperature is set. (M104, M109)
1378
   */
1379
  void Temperature::start_watching_heater(const uint8_t e) {
1380
    #if HOTENDS == 1
1381
      UNUSED(e);
1382
    #endif
1383
    if (degHotend(HOTEND_INDEX) < degTargetHotend(HOTEND_INDEX) - (WATCH_TEMP_INCREASE + TEMP_HYSTERESIS + 1)) {
1384
      watch_target_temp[HOTEND_INDEX] = degHotend(HOTEND_INDEX) + WATCH_TEMP_INCREASE;
1385
      watch_heater_next_ms[HOTEND_INDEX] = millis() + (WATCH_TEMP_PERIOD) * 1000UL;
1386
    }
1387
    else
1388
      watch_heater_next_ms[HOTEND_INDEX] = 0;
1389
  }
1390
#endif
1391
 
1392
#if WATCH_THE_BED
1393
  /**
1394
   * Start Heating Sanity Check for hotends that are below
1395
   * their target temperature by a configurable margin.
1396
   * This is called when the temperature is set. (M140, M190)
1397
   */
1398
  void Temperature::start_watching_bed() {
1399
    if (degBed() < degTargetBed() - (WATCH_BED_TEMP_INCREASE + TEMP_BED_HYSTERESIS + 1)) {
1400
      watch_target_bed_temp = degBed() + WATCH_BED_TEMP_INCREASE;
1401
      watch_bed_next_ms = millis() + (WATCH_BED_TEMP_PERIOD) * 1000UL;
1402
    }
1403
    else
1404
      watch_bed_next_ms = 0;
1405
  }
1406
#endif
1407
 
1408
#if ENABLED(THERMAL_PROTECTION_HOTENDS) || HAS_THERMALLY_PROTECTED_BED
1409
 
1410
  #if ENABLED(THERMAL_PROTECTION_HOTENDS)
1411
    Temperature::TRState Temperature::thermal_runaway_state_machine[HOTENDS] = { TRInactive };
1412
    millis_t Temperature::thermal_runaway_timer[HOTENDS] = { 0 };
1413
  #endif
1414
 
1415
  #if HAS_THERMALLY_PROTECTED_BED
1416
    Temperature::TRState Temperature::thermal_runaway_bed_state_machine = TRInactive;
1417
    millis_t Temperature::thermal_runaway_bed_timer;
1418
  #endif
1419
 
1420
  void Temperature::thermal_runaway_protection(Temperature::TRState * const state, millis_t * const timer, const float &current, const float &target, const int8_t heater_id, const uint16_t period_seconds, const uint16_t hysteresis_degc) {
1421
 
1422
    static float tr_target_temperature[HOTENDS + 1] = { 0.0 };
1423
 
1424
    /**
1425
        SERIAL_ECHO_START();
1426
        SERIAL_ECHOPGM("Thermal Thermal Runaway Running. Heater ID: ");
1427
        if (heater_id < 0) SERIAL_ECHOPGM("bed"); else SERIAL_ECHO(heater_id);
1428
        SERIAL_ECHOPAIR(" ;  State:", *state);
1429
        SERIAL_ECHOPAIR(" ;  Timer:", *timer);
1430
        SERIAL_ECHOPAIR(" ;  Temperature:", current);
1431
        SERIAL_ECHOPAIR(" ;  Target Temp:", target);
1432
        if (heater_id >= 0)
1433
          SERIAL_ECHOPAIR(" ;  Idle Timeout:", heater_idle_timeout_exceeded[heater_id]);
1434
        else
1435
          SERIAL_ECHOPAIR(" ;  Idle Timeout:", bed_idle_timeout_exceeded);
1436
        SERIAL_EOL();
1437
    */
1438
 
1439
    const int heater_index = heater_id >= 0 ? heater_id : HOTENDS;
1440
 
1441
    #if HEATER_IDLE_HANDLER
1442
      // If the heater idle timeout expires, restart
1443
      if ((heater_id >= 0 && heater_idle_timeout_exceeded[heater_id])
1444
        #if HAS_HEATED_BED
1445
          || (heater_id < 0 && bed_idle_timeout_exceeded)
1446
        #endif
1447
      ) {
1448
        *state = TRInactive;
1449
        tr_target_temperature[heater_index] = 0;
1450
      }
1451
      else
1452
    #endif
1453
    {
1454
      // If the target temperature changes, restart
1455
      if (tr_target_temperature[heater_index] != target) {
1456
        tr_target_temperature[heater_index] = target;
1457
        *state = target > 0 ? TRFirstHeating : TRInactive;
1458
      }
1459
    }
1460
 
1461
    switch (*state) {
1462
      // Inactive state waits for a target temperature to be set
1463
      case TRInactive: break;
1464
      // When first heating, wait for the temperature to be reached then go to Stable state
1465
      case TRFirstHeating:
1466
        if (current < tr_target_temperature[heater_index]) break;
1467
        *state = TRStable;
1468
      // While the temperature is stable watch for a bad temperature
1469
      case TRStable:
1470
        if (current >= tr_target_temperature[heater_index] - hysteresis_degc) {
1471
          *timer = millis() + period_seconds * 1000UL;
1472
          break;
1473
        }
1474
        else if (PENDING(millis(), *timer)) break;
1475
        *state = TRRunaway;
1476
      case TRRunaway:
1477
        _temp_error(heater_id, PSTR(MSG_T_THERMAL_RUNAWAY), TEMP_ERR_PSTR(MSG_THERMAL_RUNAWAY, heater_id));
1478
    }
1479
  }
1480
 
1481
#endif // THERMAL_PROTECTION_HOTENDS || THERMAL_PROTECTION_BED
1482
 
1483
void Temperature::disable_all_heaters() {
1484
 
1485
  #if ENABLED(AUTOTEMP)
1486
    planner.autotemp_enabled = false;
1487
  #endif
1488
 
1489
  HOTEND_LOOP() setTargetHotend(0, e);
1490
 
1491
  #if HAS_HEATED_BED
1492
    setTargetBed(0);
1493
  #endif
1494
 
1495
  // Unpause and reset everything
1496
  #if ENABLED(PROBING_HEATERS_OFF)
1497
    pause(false);
1498
  #endif
1499
 
1500
  // If all heaters go down then for sure our print job has stopped
1501
  print_job_timer.stop();
1502
 
1503
  #define DISABLE_HEATER(NR) { \
1504
    setTargetHotend(0, NR); \
1505
    soft_pwm_amount[NR] = 0; \
1506
    WRITE_HEATER_ ##NR (LOW); \
1507
  }
1508
 
1509
  #if HAS_TEMP_HOTEND
1510
    DISABLE_HEATER(0);
1511
    #if HOTENDS > 1
1512
      DISABLE_HEATER(1);
1513
      #if HOTENDS > 2
1514
        DISABLE_HEATER(2);
1515
        #if HOTENDS > 3
1516
          DISABLE_HEATER(3);
1517
          #if HOTENDS > 4
1518
            DISABLE_HEATER(4);
1519
          #endif // HOTENDS > 4
1520
        #endif // HOTENDS > 3
1521
      #endif // HOTENDS > 2
1522
    #endif // HOTENDS > 1
1523
  #endif
1524
 
1525
  #if HAS_HEATED_BED
1526
    target_temperature_bed = 0;
1527
    soft_pwm_amount_bed = 0;
1528
    #if HAS_HEATED_BED
1529
      WRITE_HEATER_BED(LOW);
1530
    #endif
1531
  #endif
1532
}
1533
 
1534
#if ENABLED(PROBING_HEATERS_OFF)
1535
 
1536
  void Temperature::pause(const bool p) {
1537
    if (p != paused) {
1538
      paused = p;
1539
      if (p) {
1540
        HOTEND_LOOP() start_heater_idle_timer(e, 0); // timeout immediately
1541
        #if HAS_HEATED_BED
1542
          start_bed_idle_timer(0); // timeout immediately
1543
        #endif
1544
      }
1545
      else {
1546
        HOTEND_LOOP() reset_heater_idle_timer(e);
1547
        #if HAS_HEATED_BED
1548
          reset_bed_idle_timer();
1549
        #endif
1550
      }
1551
    }
1552
  }
1553
 
1554
#endif // PROBING_HEATERS_OFF
1555
 
1556
#if ENABLED(HEATER_0_USES_MAX6675)
1557
 
1558
  #define MAX6675_HEAT_INTERVAL 250u
1559
 
1560
  #if ENABLED(MAX6675_IS_MAX31855)
1561
    uint32_t max6675_temp = 2000;
1562
    #define MAX6675_ERROR_MASK 7
1563
    #define MAX6675_DISCARD_BITS 18
1564
    #define MAX6675_SPEED_BITS (_BV(SPR1)) // clock ÷ 64
1565
  #else
1566
    uint16_t max6675_temp = 2000;
1567
    #define MAX6675_ERROR_MASK 4
1568
    #define MAX6675_DISCARD_BITS 3
1569
    #define MAX6675_SPEED_BITS (_BV(SPR0)) // clock ÷ 16
1570
  #endif
1571
 
1572
  int Temperature::read_max6675() {
1573
 
1574
    static millis_t next_max6675_ms = 0;
1575
 
1576
    millis_t ms = millis();
1577
 
1578
    if (PENDING(ms, next_max6675_ms)) return (int)max6675_temp;
1579
 
1580
    next_max6675_ms = ms + MAX6675_HEAT_INTERVAL;
1581
 
1582
    CBI(
1583
      #ifdef PRR
1584
        PRR
1585
      #elif defined(PRR0)
1586
        PRR0
1587
      #endif
1588
        , PRSPI);
1589
    SPCR = _BV(MSTR) | _BV(SPE) | MAX6675_SPEED_BITS;
1590
 
1591
    WRITE(MAX6675_SS, 0); // enable TT_MAX6675
1592
 
1593
    DELAY_NS(100);       // Ensure 100ns delay
1594
 
1595
    // Read a big-endian temperature value
1596
    max6675_temp = 0;
1597
    for (uint8_t i = sizeof(max6675_temp); i--;) {
1598
      max6675_temp |= max6675_spi.receive();
1599
      if (i > 0) max6675_temp <<= 8; // shift left if not the last byte
1600
    }
1601
 
1602
    WRITE(MAX6675_SS, 1); // disable TT_MAX6675
1603
 
1604
    if (max6675_temp & MAX6675_ERROR_MASK) {
1605
      SERIAL_ERROR_START();
1606
      SERIAL_ERRORPGM("Temp measurement error! ");
1607
      #if MAX6675_ERROR_MASK == 7
1608
        SERIAL_ERRORPGM("MAX31855 ");
1609
        if (max6675_temp & 1)
1610
          SERIAL_ERRORLNPGM("Open Circuit");
1611
        else if (max6675_temp & 2)
1612
          SERIAL_ERRORLNPGM("Short to GND");
1613
        else if (max6675_temp & 4)
1614
          SERIAL_ERRORLNPGM("Short to VCC");
1615
      #else
1616
        SERIAL_ERRORLNPGM("MAX6675");
1617
      #endif
1618
      max6675_temp = MAX6675_TMAX * 4; // thermocouple open
1619
    }
1620
    else
1621
      max6675_temp >>= MAX6675_DISCARD_BITS;
1622
      #if ENABLED(MAX6675_IS_MAX31855)
1623
        // Support negative temperature
1624
        if (max6675_temp & 0x00002000) max6675_temp |= 0xFFFFC000;
1625
      #endif
1626
 
1627
    return (int)max6675_temp;
1628
  }
1629
 
1630
#endif // HEATER_0_USES_MAX6675
1631
 
1632
/**
1633
 * Get raw temperatures
1634
 */
1635
void Temperature::set_current_temp_raw() {
1636
  #if HAS_TEMP_ADC_0 && DISABLED(HEATER_0_USES_MAX6675)
1637
    current_temperature_raw[0] = raw_temp_value[0];
1638
  #endif
1639
  #if HAS_TEMP_ADC_1
1640
    #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
1641
      redundant_temperature_raw = raw_temp_value[1];
1642
    #else
1643
      current_temperature_raw[1] = raw_temp_value[1];
1644
    #endif
1645
    #if HAS_TEMP_ADC_2
1646
      current_temperature_raw[2] = raw_temp_value[2];
1647
      #if HAS_TEMP_ADC_3
1648
        current_temperature_raw[3] = raw_temp_value[3];
1649
        #if HAS_TEMP_ADC_4
1650
          current_temperature_raw[4] = raw_temp_value[4];
1651
        #endif
1652
      #endif
1653
    #endif
1654
  #endif
1655
 
1656
  #if HAS_HEATED_BED
1657
    current_temperature_bed_raw = raw_temp_bed_value;
1658
  #endif
1659
  #if HAS_TEMP_CHAMBER
1660
    current_temperature_chamber_raw = raw_temp_chamber_value;
1661
  #endif
1662
  temp_meas_ready = true;
1663
}
1664
 
1665
#if ENABLED(PINS_DEBUGGING)
1666
  /**
1667
   * monitors endstops & Z probe for changes
1668
   *
1669
   * If a change is detected then the LED is toggled and
1670
   * a message is sent out the serial port
1671
   *
1672
   * Yes, we could miss a rapid back & forth change but
1673
   * that won't matter because this is all manual.
1674
   *
1675
   */
1676
  void endstop_monitor() {
1677
    static uint16_t old_live_state_local = 0;
1678
    static uint8_t local_LED_status = 0;
1679
    uint16_t live_state_local = 0;
1680
    #if HAS_X_MIN
1681
      if (READ(X_MIN_PIN)) SBI(live_state_local, X_MIN);
1682
    #endif
1683
    #if HAS_X_MAX
1684
      if (READ(X_MAX_PIN)) SBI(live_state_local, X_MAX);
1685
    #endif
1686
    #if HAS_Y_MIN
1687
      if (READ(Y_MIN_PIN)) SBI(live_state_local, Y_MIN);
1688
    #endif
1689
    #if HAS_Y_MAX
1690
      if (READ(Y_MAX_PIN)) SBI(live_state_local, Y_MAX);
1691
    #endif
1692
    #if HAS_Z_MIN
1693
      if (READ(Z_MIN_PIN)) SBI(live_state_local, Z_MIN);
1694
    #endif
1695
    #if HAS_Z_MAX
1696
      if (READ(Z_MAX_PIN)) SBI(live_state_local, Z_MAX);
1697
    #endif
1698
    #if HAS_Z_MIN_PROBE_PIN
1699
      if (READ(Z_MIN_PROBE_PIN)) SBI(live_state_local, Z_MIN_PROBE);
1700
    #endif
1701
    #if HAS_Z2_MIN
1702
      if (READ(Z2_MIN_PIN)) SBI(live_state_local, Z2_MIN);
1703
    #endif
1704
    #if HAS_Z2_MAX
1705
      if (READ(Z2_MAX_PIN)) SBI(live_state_local, Z2_MAX);
1706
    #endif
1707
 
1708
    uint16_t endstop_change = live_state_local ^ old_live_state_local;
1709
 
1710
    if (endstop_change) {
1711
      #if HAS_X_MIN
1712
        if (TEST(endstop_change, X_MIN)) SERIAL_PROTOCOLPAIR("  X_MIN:", !!TEST(live_state_local, X_MIN));
1713
      #endif
1714
      #if HAS_X_MAX
1715
        if (TEST(endstop_change, X_MAX)) SERIAL_PROTOCOLPAIR("  X_MAX:", !!TEST(live_state_local, X_MAX));
1716
      #endif
1717
      #if HAS_Y_MIN
1718
        if (TEST(endstop_change, Y_MIN)) SERIAL_PROTOCOLPAIR("  Y_MIN:", !!TEST(live_state_local, Y_MIN));
1719
      #endif
1720
      #if HAS_Y_MAX
1721
        if (TEST(endstop_change, Y_MAX)) SERIAL_PROTOCOLPAIR("  Y_MAX:", !!TEST(live_state_local, Y_MAX));
1722
      #endif
1723
      #if HAS_Z_MIN
1724
        if (TEST(endstop_change, Z_MIN)) SERIAL_PROTOCOLPAIR("  Z_MIN:", !!TEST(live_state_local, Z_MIN));
1725
      #endif
1726
      #if HAS_Z_MAX
1727
        if (TEST(endstop_change, Z_MAX)) SERIAL_PROTOCOLPAIR("  Z_MAX:", !!TEST(live_state_local, Z_MAX));
1728
      #endif
1729
      #if HAS_Z_MIN_PROBE_PIN
1730
        if (TEST(endstop_change, Z_MIN_PROBE)) SERIAL_PROTOCOLPAIR("  PROBE:", !!TEST(live_state_local, Z_MIN_PROBE));
1731
      #endif
1732
      #if HAS_Z2_MIN
1733
        if (TEST(endstop_change, Z2_MIN)) SERIAL_PROTOCOLPAIR("  Z2_MIN:", !!TEST(live_state_local, Z2_MIN));
1734
      #endif
1735
      #if HAS_Z2_MAX
1736
        if (TEST(endstop_change, Z2_MAX)) SERIAL_PROTOCOLPAIR("  Z2_MAX:", !!TEST(live_state_local, Z2_MAX));
1737
      #endif
1738
      SERIAL_PROTOCOLPGM("\n\n");
1739
      analogWrite(LED_PIN, local_LED_status);
1740
      local_LED_status ^= 255;
1741
      old_live_state_local = live_state_local;
1742
    }
1743
  }
1744
#endif // PINS_DEBUGGING
1745
 
1746
#if ENABLED(FILAMENT_WIDTH_SENSOR)
1747
  uint32_t raw_filwidth_value; // = 0
1748
#endif
1749
 
1750
void Temperature::readings_ready() {
1751
  // Update the raw values if they've been read. Else we could be updating them during reading.
1752
  if (!temp_meas_ready) set_current_temp_raw();
1753
 
1754
  // Filament Sensor - can be read any time since IIR filtering is used
1755
  #if ENABLED(FILAMENT_WIDTH_SENSOR)
1756
    current_raw_filwidth = raw_filwidth_value >> 10;  // Divide to get to 0-16384 range since we used 1/128 IIR filter approach
1757
  #endif
1758
 
1759
  ZERO(raw_temp_value);
1760
 
1761
  #if HAS_HEATED_BED
1762
    raw_temp_bed_value = 0;
1763
  #endif
1764
 
1765
  #if HAS_TEMP_CHAMBER
1766
    raw_temp_chamber_value = 0;
1767
  #endif
1768
 
1769
  #define TEMPDIR(N) ((HEATER_##N##_RAW_LO_TEMP) > (HEATER_##N##_RAW_HI_TEMP) ? -1 : 1)
1770
 
1771
  int constexpr temp_dir[] = {
1772
    #if ENABLED(HEATER_0_USES_MAX6675)
1773
 
1774
    #else
1775
      TEMPDIR(0)
1776
    #endif
1777
    #if HOTENDS > 1
1778
      , TEMPDIR(1)
1779
      #if HOTENDS > 2
1780
        , TEMPDIR(2)
1781
        #if HOTENDS > 3
1782
          , TEMPDIR(3)
1783
          #if HOTENDS > 4
1784
            , TEMPDIR(4)
1785
          #endif // HOTENDS > 4
1786
        #endif // HOTENDS > 3
1787
      #endif // HOTENDS > 2
1788
    #endif // HOTENDS > 1
1789
  };
1790
 
1791
  for (uint8_t e = 0; e < COUNT(temp_dir); e++) {
1792
    const int16_t tdir = temp_dir[e], rawtemp = current_temperature_raw[e] * tdir;
1793
    const bool heater_on = (target_temperature[e] > 0)
1794
      #if ENABLED(PIDTEMP)
1795
        || (soft_pwm_amount[e] > 0)
1796
      #endif
1797
    ;
1798
    if (rawtemp > maxttemp_raw[e] * tdir) max_temp_error(e);
1799
    if (rawtemp < minttemp_raw[e] * tdir && !is_preheating(e) && heater_on) {
1800
      #ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
1801
        if (++consecutive_low_temperature_error[e] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
1802
      #endif
1803
          min_temp_error(e);
1804
    }
1805
    #ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
1806
      else
1807
        consecutive_low_temperature_error[e] = 0;
1808
    #endif
1809
  }
1810
 
1811
  #if HAS_HEATED_BED
1812
    #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
1813
      #define GEBED <=
1814
    #else
1815
      #define GEBED >=
1816
    #endif
1817
    const bool bed_on = (target_temperature_bed > 0)
1818
      #if ENABLED(PIDTEMPBED)
1819
        || (soft_pwm_amount_bed > 0)
1820
      #endif
1821
    ;
1822
    if (current_temperature_bed_raw GEBED bed_maxttemp_raw) max_temp_error(-1);
1823
    if (bed_minttemp_raw GEBED current_temperature_bed_raw && bed_on) min_temp_error(-1);
1824
  #endif
1825
}
1826
 
1827
/**
1828
 * Timer 0 is shared with millis so don't change the prescaler.
1829
 *
1830
 * This ISR uses the compare method so it runs at the base
1831
 * frequency (16 MHz / 64 / 256 = 976.5625 Hz), but at the TCNT0 set
1832
 * in OCR0B above (128 or halfway between OVFs).
1833
 *
1834
 *  - Manage PWM to all the heaters and fan
1835
 *  - Prepare or Measure one of the raw ADC sensor values
1836
 *  - Check new temperature values for MIN/MAX errors (kill on error)
1837
 *  - Step the babysteps value for each axis towards 0
1838
 *  - For PINS_DEBUGGING, monitor and report endstop pins
1839
 *  - For ENDSTOP_INTERRUPTS_FEATURE check endstops if flagged
1840
 *  - Call planner.tick to count down its "ignore" time
1841
 */
1842
HAL_TEMP_TIMER_ISR {
1843
  HAL_timer_isr_prologue(TEMP_TIMER_NUM);
1844
 
1845
  Temperature::isr();
1846
 
1847
  HAL_timer_isr_epilogue(TEMP_TIMER_NUM);
1848
}
1849
 
1850
void Temperature::isr() {
1851
 
1852
  static int8_t temp_count = -1;
1853
  static ADCSensorState adc_sensor_state = StartupDelay;
1854
  static uint8_t pwm_count = _BV(SOFT_PWM_SCALE);
1855
  // avoid multiple loads of pwm_count
1856
  uint8_t pwm_count_tmp = pwm_count;
1857
  #if ENABLED(ADC_KEYPAD)
1858
    static unsigned int raw_ADCKey_value = 0;
1859
  #endif
1860
 
1861
  // Static members for each heater
1862
  #if ENABLED(SLOW_PWM_HEATERS)
1863
    static uint8_t slow_pwm_count = 0;
1864
    #define ISR_STATICS(n) \
1865
      static uint8_t soft_pwm_count_ ## n, \
1866
                     state_heater_ ## n = 0, \
1867
                     state_timer_heater_ ## n = 0
1868
  #else
1869
    #define ISR_STATICS(n) static uint8_t soft_pwm_count_ ## n = 0
1870
  #endif
1871
 
1872
  // Statics per heater
1873
  ISR_STATICS(0);
1874
  #if HOTENDS > 1
1875
    ISR_STATICS(1);
1876
    #if HOTENDS > 2
1877
      ISR_STATICS(2);
1878
      #if HOTENDS > 3
1879
        ISR_STATICS(3);
1880
        #if HOTENDS > 4
1881
          ISR_STATICS(4);
1882
        #endif // HOTENDS > 4
1883
      #endif // HOTENDS > 3
1884
    #endif // HOTENDS > 2
1885
  #endif // HOTENDS > 1
1886
  #if HAS_HEATED_BED
1887
    ISR_STATICS(BED);
1888
  #endif
1889
 
1890
  #if DISABLED(SLOW_PWM_HEATERS)
1891
    constexpr uint8_t pwm_mask =
1892
      #if ENABLED(SOFT_PWM_DITHER)
1893
        _BV(SOFT_PWM_SCALE) - 1
1894
      #else
1895
 
1896
      #endif
1897
    ;
1898
 
1899
    /**
1900
     * Standard PWM modulation
1901
     */
1902
    if (pwm_count_tmp >= 127) {
1903
      pwm_count_tmp -= 127;
1904
      soft_pwm_count_0 = (soft_pwm_count_0 & pwm_mask) + soft_pwm_amount[0];
1905
      WRITE_HEATER_0(soft_pwm_count_0 > pwm_mask ? HIGH : LOW);
1906
      #if HOTENDS > 1
1907
        soft_pwm_count_1 = (soft_pwm_count_1 & pwm_mask) + soft_pwm_amount[1];
1908
        WRITE_HEATER_1(soft_pwm_count_1 > pwm_mask ? HIGH : LOW);
1909
        #if HOTENDS > 2
1910
          soft_pwm_count_2 = (soft_pwm_count_2 & pwm_mask) + soft_pwm_amount[2];
1911
          WRITE_HEATER_2(soft_pwm_count_2 > pwm_mask ? HIGH : LOW);
1912
          #if HOTENDS > 3
1913
            soft_pwm_count_3 = (soft_pwm_count_3 & pwm_mask) + soft_pwm_amount[3];
1914
            WRITE_HEATER_3(soft_pwm_count_3 > pwm_mask ? HIGH : LOW);
1915
            #if HOTENDS > 4
1916
              soft_pwm_count_4 = (soft_pwm_count_4 & pwm_mask) + soft_pwm_amount[4];
1917
              WRITE_HEATER_4(soft_pwm_count_4 > pwm_mask ? HIGH : LOW);
1918
            #endif // HOTENDS > 4
1919
          #endif // HOTENDS > 3
1920
        #endif // HOTENDS > 2
1921
      #endif // HOTENDS > 1
1922
 
1923
      #if HAS_HEATED_BED
1924
        soft_pwm_count_BED = (soft_pwm_count_BED & pwm_mask) + soft_pwm_amount_bed;
1925
        WRITE_HEATER_BED(soft_pwm_count_BED > pwm_mask ? HIGH : LOW);
1926
      #endif
1927
 
1928
      #if ENABLED(FAN_SOFT_PWM)
1929
        #if HAS_FAN0
1930
          soft_pwm_count_fan[0] = (soft_pwm_count_fan[0] & pwm_mask) + (soft_pwm_amount_fan[0] >> 1);
1931
          WRITE_FAN(soft_pwm_count_fan[0] > pwm_mask ? HIGH : LOW);
1932
        #endif
1933
        #if HAS_FAN1
1934
          soft_pwm_count_fan[1] = (soft_pwm_count_fan[1] & pwm_mask) + (soft_pwm_amount_fan[1] >> 1);
1935
          WRITE_FAN1(soft_pwm_count_fan[1] > pwm_mask ? HIGH : LOW);
1936
        #endif
1937
        #if HAS_FAN2
1938
          soft_pwm_count_fan[2] = (soft_pwm_count_fan[2] & pwm_mask) + (soft_pwm_amount_fan[2] >> 1);
1939
          WRITE_FAN2(soft_pwm_count_fan[2] > pwm_mask ? HIGH : LOW);
1940
        #endif
1941
      #endif
1942
    }
1943
    else {
1944
      if (soft_pwm_count_0 <= pwm_count_tmp) WRITE_HEATER_0(LOW);
1945
      #if HOTENDS > 1
1946
        if (soft_pwm_count_1 <= pwm_count_tmp) WRITE_HEATER_1(LOW);
1947
        #if HOTENDS > 2
1948
          if (soft_pwm_count_2 <= pwm_count_tmp) WRITE_HEATER_2(LOW);
1949
          #if HOTENDS > 3
1950
            if (soft_pwm_count_3 <= pwm_count_tmp) WRITE_HEATER_3(LOW);
1951
            #if HOTENDS > 4
1952
              if (soft_pwm_count_4 <= pwm_count_tmp) WRITE_HEATER_4(LOW);
1953
            #endif // HOTENDS > 4
1954
          #endif // HOTENDS > 3
1955
        #endif // HOTENDS > 2
1956
      #endif // HOTENDS > 1
1957
 
1958
      #if HAS_HEATED_BED
1959
        if (soft_pwm_count_BED <= pwm_count_tmp) WRITE_HEATER_BED(LOW);
1960
      #endif
1961
 
1962
      #if ENABLED(FAN_SOFT_PWM)
1963
        #if HAS_FAN0
1964
          if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(LOW);
1965
        #endif
1966
        #if HAS_FAN1
1967
          if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN1(LOW);
1968
        #endif
1969
        #if HAS_FAN2
1970
          if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN2(LOW);
1971
        #endif
1972
      #endif
1973
    }
1974
 
1975
    // SOFT_PWM_SCALE to frequency:
1976
    //
1977
    // 0: 16000000/64/256/128 =   7.6294 Hz
1978
    // 1:                / 64 =  15.2588 Hz
1979
    // 2:                / 32 =  30.5176 Hz
1980
    // 3:                / 16 =  61.0352 Hz
1981
    // 4:                /  8 = 122.0703 Hz
1982
    // 5:                /  4 = 244.1406 Hz
1983
    pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
1984
 
1985
  #else // SLOW_PWM_HEATERS
1986
 
1987
    /**
1988
     * SLOW PWM HEATERS
1989
     *
1990
     * For relay-driven heaters
1991
     */
1992
    #ifndef MIN_STATE_TIME
1993
      #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
1994
    #endif
1995
 
1996
    // Macros for Slow PWM timer logic
1997
    #define _SLOW_PWM_ROUTINE(NR, src) \
1998
      soft_pwm_count_ ##NR = src; \
1999
      if (soft_pwm_count_ ##NR > 0) { \
2000
        if (state_timer_heater_ ##NR == 0) { \
2001
          if (state_heater_ ##NR == 0) state_timer_heater_ ##NR = MIN_STATE_TIME; \
2002
          state_heater_ ##NR = 1; \
2003
          WRITE_HEATER_ ##NR(1); \
2004
        } \
2005
      } \
2006
      else { \
2007
        if (state_timer_heater_ ##NR == 0) { \
2008
          if (state_heater_ ##NR == 1) state_timer_heater_ ##NR = MIN_STATE_TIME; \
2009
          state_heater_ ##NR = 0; \
2010
          WRITE_HEATER_ ##NR(0); \
2011
        } \
2012
      }
2013
    #define SLOW_PWM_ROUTINE(n) _SLOW_PWM_ROUTINE(n, soft_pwm_amount[n])
2014
 
2015
    #define PWM_OFF_ROUTINE(NR) \
2016
      if (soft_pwm_count_ ##NR < slow_pwm_count) { \
2017
        if (state_timer_heater_ ##NR == 0) { \
2018
          if (state_heater_ ##NR == 1) state_timer_heater_ ##NR = MIN_STATE_TIME; \
2019
          state_heater_ ##NR = 0; \
2020
          WRITE_HEATER_ ##NR (0); \
2021
        } \
2022
      }
2023
 
2024
    if (slow_pwm_count == 0) {
2025
 
2026
      SLOW_PWM_ROUTINE(0);
2027
      #if HOTENDS > 1
2028
        SLOW_PWM_ROUTINE(1);
2029
        #if HOTENDS > 2
2030
          SLOW_PWM_ROUTINE(2);
2031
          #if HOTENDS > 3
2032
            SLOW_PWM_ROUTINE(3);
2033
            #if HOTENDS > 4
2034
              SLOW_PWM_ROUTINE(4);
2035
            #endif // HOTENDS > 4
2036
          #endif // HOTENDS > 3
2037
        #endif // HOTENDS > 2
2038
      #endif // HOTENDS > 1
2039
      #if HAS_HEATED_BED
2040
        _SLOW_PWM_ROUTINE(BED, soft_pwm_amount_bed); // BED
2041
      #endif
2042
 
2043
    } // slow_pwm_count == 0
2044
 
2045
    PWM_OFF_ROUTINE(0);
2046
    #if HOTENDS > 1
2047
      PWM_OFF_ROUTINE(1);
2048
      #if HOTENDS > 2
2049
        PWM_OFF_ROUTINE(2);
2050
        #if HOTENDS > 3
2051
          PWM_OFF_ROUTINE(3);
2052
          #if HOTENDS > 4
2053
            PWM_OFF_ROUTINE(4);
2054
          #endif // HOTENDS > 4
2055
        #endif // HOTENDS > 3
2056
      #endif // HOTENDS > 2
2057
    #endif // HOTENDS > 1
2058
    #if HAS_HEATED_BED
2059
      PWM_OFF_ROUTINE(BED); // BED
2060
    #endif
2061
 
2062
    #if ENABLED(FAN_SOFT_PWM)
2063
      if (pwm_count_tmp >= 127) {
2064
        pwm_count_tmp = 0;
2065
        #if HAS_FAN0
2066
          soft_pwm_count_fan[0] = soft_pwm_amount_fan[0] >> 1;
2067
          WRITE_FAN(soft_pwm_count_fan[0] > 0 ? HIGH : LOW);
2068
        #endif
2069
        #if HAS_FAN1
2070
          soft_pwm_count_fan[1] = soft_pwm_amount_fan[1] >> 1;
2071
          WRITE_FAN1(soft_pwm_count_fan[1] > 0 ? HIGH : LOW);
2072
        #endif
2073
        #if HAS_FAN2
2074
          soft_pwm_count_fan[2] = soft_pwm_amount_fan[2] >> 1;
2075
          WRITE_FAN2(soft_pwm_count_fan[2] > 0 ? HIGH : LOW);
2076
        #endif
2077
      }
2078
      #if HAS_FAN0
2079
        if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(LOW);
2080
      #endif
2081
      #if HAS_FAN1
2082
        if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN1(LOW);
2083
      #endif
2084
      #if HAS_FAN2
2085
        if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN2(LOW);
2086
      #endif
2087
    #endif // FAN_SOFT_PWM
2088
 
2089
    // SOFT_PWM_SCALE to frequency:
2090
    //
2091
    // 0: 16000000/64/256/128 =   7.6294 Hz
2092
    // 1:                / 64 =  15.2588 Hz
2093
    // 2:                / 32 =  30.5176 Hz
2094
    // 3:                / 16 =  61.0352 Hz
2095
    // 4:                /  8 = 122.0703 Hz
2096
    // 5:                /  4 = 244.1406 Hz
2097
    pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
2098
 
2099
    // increment slow_pwm_count only every 64th pwm_count,
2100
    // i.e. yielding a PWM frequency of 16/128 Hz (8s).
2101
    if (((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0) {
2102
      slow_pwm_count++;
2103
      slow_pwm_count &= 0x7F;
2104
 
2105
      if (state_timer_heater_0 > 0) state_timer_heater_0--;
2106
      #if HOTENDS > 1
2107
        if (state_timer_heater_1 > 0) state_timer_heater_1--;
2108
        #if HOTENDS > 2
2109
          if (state_timer_heater_2 > 0) state_timer_heater_2--;
2110
          #if HOTENDS > 3
2111
            if (state_timer_heater_3 > 0) state_timer_heater_3--;
2112
            #if HOTENDS > 4
2113
              if (state_timer_heater_4 > 0) state_timer_heater_4--;
2114
            #endif // HOTENDS > 4
2115
          #endif // HOTENDS > 3
2116
        #endif // HOTENDS > 2
2117
      #endif // HOTENDS > 1
2118
      #if HAS_HEATED_BED
2119
        if (state_timer_heater_BED > 0) state_timer_heater_BED--;
2120
      #endif
2121
    } // ((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0
2122
 
2123
  #endif // SLOW_PWM_HEATERS
2124
 
2125
  //
2126
  // Update lcd buttons 488 times per second
2127
  //
2128
  static bool do_buttons;
2129
  if ((do_buttons ^= true)) lcd_buttons_update();
2130
 
2131
  /**
2132
   * One sensor is sampled on every other call of the ISR.
2133
   * Each sensor is read 16 (OVERSAMPLENR) times, taking the average.
2134
   *
2135
   * On each Prepare pass, ADC is started for a sensor pin.
2136
   * On the next pass, the ADC value is read and accumulated.
2137
   *
2138
   * This gives each ADC 0.9765ms to charge up.
2139
   */
2140
  #define ACCUMULATE_ADC(var) do{ \
2141
    if (!HAL_ADC_READY()) next_sensor_state = adc_sensor_state; \
2142
    else var += HAL_READ_ADC(); \
2143
  }while(0)
2144
 
2145
  ADCSensorState next_sensor_state = adc_sensor_state < SensorsReady ? (ADCSensorState)(int(adc_sensor_state) + 1) : StartSampling;
2146
 
2147
  switch (adc_sensor_state) {
2148
 
2149
    case SensorsReady: {
2150
      // All sensors have been read. Stay in this state for a few
2151
      // ISRs to save on calls to temp update/checking code below.
2152
      constexpr int8_t extra_loops = MIN_ADC_ISR_LOOPS - (int8_t)SensorsReady;
2153
      static uint8_t delay_count = 0;
2154
      if (extra_loops > 0) {
2155
        if (delay_count == 0) delay_count = extra_loops;  // Init this delay
2156
        if (--delay_count)                                // While delaying...
2157
          next_sensor_state = SensorsReady;               // retain this state (else, next state will be 0)
2158
        break;
2159
      }
2160
      else {
2161
        adc_sensor_state = StartSampling;                 // Fall-through to start sampling
2162
        next_sensor_state = (ADCSensorState)(int(StartSampling) + 1);
2163
      }
2164
    }
2165
 
2166
    case StartSampling:                                   // Start of sampling loops. Do updates/checks.
2167
      if (++temp_count >= OVERSAMPLENR) {                 // 10 * 16 * 1/(16000000/64/256)  = 164ms.
2168
        temp_count = 0;
2169
        readings_ready();
2170
      }
2171
      break;
2172
 
2173
    #if HAS_TEMP_ADC_0
2174
      case PrepareTemp_0:
2175
        HAL_START_ADC(TEMP_0_PIN);
2176
        break;
2177
      case MeasureTemp_0:
2178
        ACCUMULATE_ADC(raw_temp_value[0]);
2179
        break;
2180
    #endif
2181
 
2182
    #if HAS_HEATED_BED
2183
      case PrepareTemp_BED:
2184
        HAL_START_ADC(TEMP_BED_PIN);
2185
        break;
2186
      case MeasureTemp_BED:
2187
        ACCUMULATE_ADC(raw_temp_bed_value);
2188
        break;
2189
    #endif
2190
 
2191
    #if HAS_TEMP_CHAMBER
2192
      case PrepareTemp_CHAMBER:
2193
        HAL_START_ADC(TEMP_CHAMBER_PIN);
2194
        break;
2195
      case MeasureTemp_CHAMBER:
2196
        ACCUMULATE_ADC(raw_temp_chamber_value);
2197
        break;
2198
    #endif
2199
 
2200
    #if HAS_TEMP_ADC_1
2201
      case PrepareTemp_1:
2202
        HAL_START_ADC(TEMP_1_PIN);
2203
        break;
2204
      case MeasureTemp_1:
2205
        ACCUMULATE_ADC(raw_temp_value[1]);
2206
        break;
2207
    #endif
2208
 
2209
    #if HAS_TEMP_ADC_2
2210
      case PrepareTemp_2:
2211
        HAL_START_ADC(TEMP_2_PIN);
2212
        break;
2213
      case MeasureTemp_2:
2214
        ACCUMULATE_ADC(raw_temp_value[2]);
2215
        break;
2216
    #endif
2217
 
2218
    #if HAS_TEMP_ADC_3
2219
      case PrepareTemp_3:
2220
        HAL_START_ADC(TEMP_3_PIN);
2221
        break;
2222
      case MeasureTemp_3:
2223
        ACCUMULATE_ADC(raw_temp_value[3]);
2224
        break;
2225
    #endif
2226
 
2227
    #if HAS_TEMP_ADC_4
2228
      case PrepareTemp_4:
2229
        HAL_START_ADC(TEMP_4_PIN);
2230
        break;
2231
      case MeasureTemp_4:
2232
        ACCUMULATE_ADC(raw_temp_value[4]);
2233
        break;
2234
    #endif
2235
 
2236
    #if ENABLED(FILAMENT_WIDTH_SENSOR)
2237
      case Prepare_FILWIDTH:
2238
        HAL_START_ADC(FILWIDTH_PIN);
2239
      break;
2240
      case Measure_FILWIDTH:
2241
        if (!HAL_ADC_READY())
2242
          next_sensor_state = adc_sensor_state; // redo this state
2243
        else if (HAL_READ_ADC() > 102) { // Make sure ADC is reading > 0.5 volts, otherwise don't read.
2244
          raw_filwidth_value -= raw_filwidth_value >> 7; // Subtract 1/128th of the raw_filwidth_value
2245
          raw_filwidth_value += uint32_t(HAL_READ_ADC()) << 7; // Add new ADC reading, scaled by 128
2246
        }
2247
      break;
2248
    #endif
2249
 
2250
    #if ENABLED(ADC_KEYPAD)
2251
      case Prepare_ADC_KEY:
2252
        HAL_START_ADC(ADC_KEYPAD_PIN);
2253
        break;
2254
      case Measure_ADC_KEY:
2255
        if (!HAL_ADC_READY())
2256
          next_sensor_state = adc_sensor_state; // redo this state
2257
        else if (ADCKey_count < 16) {
2258
          raw_ADCKey_value = HAL_READ_ADC();
2259
          if (raw_ADCKey_value > 900) {
2260
            //ADC Key release
2261
            ADCKey_count = 0;
2262
            current_ADCKey_raw = 0;
2263
          }
2264
          else {
2265
            current_ADCKey_raw += raw_ADCKey_value;
2266
            ADCKey_count++;
2267
          }
2268
        }
2269
        break;
2270
    #endif // ADC_KEYPAD
2271
 
2272
    case StartupDelay: break;
2273
 
2274
  } // switch(adc_sensor_state)
2275
 
2276
  // Go to the next state
2277
  adc_sensor_state = next_sensor_state;
2278
 
2279
  //
2280
  // Additional ~1KHz Tasks
2281
  //
2282
 
2283
  #if ENABLED(BABYSTEPPING)
2284
    LOOP_XYZ(axis) {
2285
      const int curTodo = babystepsTodo[axis]; // get rid of volatile for performance
2286
      if (curTodo) {
2287
        stepper.babystep((AxisEnum)axis, curTodo > 0);
2288
        if (curTodo > 0) babystepsTodo[axis]--;
2289
                    else babystepsTodo[axis]++;
2290
      }
2291
    }
2292
  #endif // BABYSTEPPING
2293
 
2294
  // Poll endstops state, if required
2295
  endstops.poll();
2296
 
2297
  // Periodically call the planner timer
2298
  planner.tick();
2299
}
2300
 
2301
#if HAS_TEMP_SENSOR
2302
 
2303
  void print_heater_state(const float &c, const float &t,
2304
    #if ENABLED(SHOW_TEMP_ADC_VALUES)
2305
      const float r,
2306
    #endif
2307
    const int8_t e=-3
2308
  ) {
2309
    #if !(HAS_HEATED_BED && HAS_TEMP_HOTEND && HAS_TEMP_CHAMBER) && HOTENDS <= 1
2310
      UNUSED(e);
2311
    #endif
2312
 
2313
    SERIAL_PROTOCOLCHAR(' ');
2314
    SERIAL_PROTOCOLCHAR(
2315
      #if HAS_TEMP_CHAMBER && HAS_HEATED_BED && HAS_TEMP_HOTEND
2316
        e == -2 ? 'C' : e == -1 ? 'B' : 'T'
2317
      #elif HAS_HEATED_BED && HAS_TEMP_HOTEND
2318
        e == -1 ? 'B' : 'T'
2319
      #elif HAS_TEMP_HOTEND
2320
        'T'
2321
      #else
2322
        'B'
2323
      #endif
2324
    );
2325
    #if HOTENDS > 1
2326
      if (e >= 0) SERIAL_PROTOCOLCHAR('0' + e);
2327
    #endif
2328
    SERIAL_PROTOCOLCHAR(':');
2329
    SERIAL_PROTOCOL(c);
2330
    SERIAL_PROTOCOLPAIR(" /" , t);
2331
    #if ENABLED(SHOW_TEMP_ADC_VALUES)
2332
      SERIAL_PROTOCOLPAIR(" (", r / OVERSAMPLENR);
2333
      SERIAL_PROTOCOLCHAR(')');
2334
    #endif
2335
    delay(2);
2336
  }
2337
 
2338
  extern uint8_t target_extruder;
2339
 
2340
  void Temperature::print_heaterstates() {
2341
    #if HAS_TEMP_HOTEND
2342
      print_heater_state(degHotend(target_extruder), degTargetHotend(target_extruder)
2343
        #if ENABLED(SHOW_TEMP_ADC_VALUES)
2344
          , rawHotendTemp(target_extruder)
2345
        #endif
2346
      );
2347
    #endif
2348
    #if HAS_HEATED_BED
2349
      print_heater_state(degBed(), degTargetBed()
2350
        #if ENABLED(SHOW_TEMP_ADC_VALUES)
2351
          , rawBedTemp()
2352
        #endif
2353
        , -1 // BED
2354
      );
2355
    #endif
2356
    #if HAS_TEMP_CHAMBER
2357
      print_heater_state(degChamber(), 0
2358
        #if ENABLED(SHOW_TEMP_ADC_VALUES)
2359
          , rawChamberTemp()
2360
        #endif
2361
        , -2 // CHAMBER
2362
      );
2363
    #endif
2364
    #if HOTENDS > 1
2365
      HOTEND_LOOP() print_heater_state(degHotend(e), degTargetHotend(e)
2366
        #if ENABLED(SHOW_TEMP_ADC_VALUES)
2367
          , rawHotendTemp(e)
2368
        #endif
2369
        , e
2370
      );
2371
    #endif
2372
    SERIAL_PROTOCOLPGM(" @:");
2373
    SERIAL_PROTOCOL(getHeaterPower(target_extruder));
2374
    #if HAS_HEATED_BED
2375
      SERIAL_PROTOCOLPGM(" B@:");
2376
      SERIAL_PROTOCOL(getHeaterPower(-1));
2377
    #endif
2378
    #if HOTENDS > 1
2379
      HOTEND_LOOP() {
2380
        SERIAL_PROTOCOLPAIR(" @", e);
2381
        SERIAL_PROTOCOLCHAR(':');
2382
        SERIAL_PROTOCOL(getHeaterPower(e));
2383
      }
2384
    #endif
2385
  }
2386
 
2387
  #if ENABLED(AUTO_REPORT_TEMPERATURES)
2388
 
2389
    uint8_t Temperature::auto_report_temp_interval;
2390
    millis_t Temperature::next_temp_report_ms;
2391
 
2392
    void Temperature::auto_report_temperatures() {
2393
      if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
2394
        next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
2395
        print_heaterstates();
2396
        SERIAL_EOL();
2397
      }
2398
    }
2399
 
2400
  #endif // AUTO_REPORT_TEMPERATURES
2401
 
2402
#endif // HAS_TEMP_SENSOR