My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

temperature.cpp 54KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  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. temperature.cpp - temperature control
  24. Part of Marlin
  25. Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  26. This program is free software: you can redistribute it and/or modify
  27. it under the terms of the GNU General Public License as published by
  28. the Free Software Foundation, either version 3 of the License, or
  29. (at your option) any later version.
  30. This program is distributed in the hope that it will be useful,
  31. but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. GNU General Public License for more details.
  34. You should have received a copy of the GNU General Public License
  35. along with this program. If not, see <http://www.gnu.org/licenses/>.
  36. */
  37. #include "Marlin.h"
  38. #include "ultralcd.h"
  39. #include "temperature.h"
  40. #include "language.h"
  41. #include "Sd2PinMap.h"
  42. #if ENABLED(USE_WATCHDOG)
  43. #include "watchdog.h"
  44. #endif
  45. //===========================================================================
  46. //================================== macros =================================
  47. //===========================================================================
  48. #ifdef K1 // Defined in Configuration.h in the PID settings
  49. #define K2 (1.0-K1)
  50. #endif
  51. #if ENABLED(PIDTEMPBED) || ENABLED(PIDTEMP)
  52. #define PID_dT ((OVERSAMPLENR * 12.0)/(F_CPU / 64.0 / 256.0))
  53. #endif
  54. //===========================================================================
  55. //============================= public variables ============================
  56. //===========================================================================
  57. int target_temperature[4] = { 0 };
  58. int target_temperature_bed = 0;
  59. int current_temperature_raw[4] = { 0 };
  60. float current_temperature[4] = { 0.0 };
  61. int current_temperature_bed_raw = 0;
  62. float current_temperature_bed = 0.0;
  63. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  64. int redundant_temperature_raw = 0;
  65. float redundant_temperature = 0.0;
  66. #endif
  67. #if ENABLED(PIDTEMPBED)
  68. float bedKp = DEFAULT_bedKp;
  69. float bedKi = (DEFAULT_bedKi* PID_dT);
  70. float bedKd = (DEFAULT_bedKd / PID_dT);
  71. #endif //PIDTEMPBED
  72. #if ENABLED(FAN_SOFT_PWM)
  73. unsigned char fanSpeedSoftPwm[FAN_COUNT];
  74. #endif
  75. unsigned char soft_pwm_bed;
  76. #if ENABLED(BABYSTEPPING)
  77. volatile int babystepsTodo[3] = { 0 };
  78. #endif
  79. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  80. int current_raw_filwidth = 0; //Holds measured filament diameter - one extruder only
  81. #endif
  82. #if ENABLED(THERMAL_PROTECTION_HOTENDS) || ENABLED(THERMAL_PROTECTION_BED)
  83. enum TRState { TRReset, TRInactive, TRFirstHeating, TRStable, TRRunaway };
  84. void thermal_runaway_protection(TRState* state, millis_t* timer, float temperature, float target_temperature, int heater_id, int period_seconds, int hysteresis_degc);
  85. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  86. static TRState thermal_runaway_state_machine[4] = { TRReset, TRReset, TRReset, TRReset };
  87. static millis_t thermal_runaway_timer[4]; // = {0,0,0,0};
  88. #endif
  89. #if ENABLED(THERMAL_PROTECTION_BED) && TEMP_SENSOR_BED != 0
  90. static TRState thermal_runaway_bed_state_machine = TRReset;
  91. static millis_t thermal_runaway_bed_timer;
  92. #endif
  93. #endif
  94. //===========================================================================
  95. //============================ private variables ============================
  96. //===========================================================================
  97. static volatile bool temp_meas_ready = false;
  98. #if ENABLED(PIDTEMP)
  99. //static cannot be external:
  100. static float temp_iState[EXTRUDERS] = { 0 };
  101. static float temp_dState[EXTRUDERS] = { 0 };
  102. static float pTerm[EXTRUDERS];
  103. static float iTerm[EXTRUDERS];
  104. static float dTerm[EXTRUDERS];
  105. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  106. static float cTerm[EXTRUDERS];
  107. static long last_position[EXTRUDERS];
  108. static long lpq[LPQ_MAX_LEN];
  109. static int lpq_ptr = 0;
  110. #endif
  111. //int output;
  112. static float pid_error[EXTRUDERS];
  113. static float temp_iState_min[EXTRUDERS];
  114. static float temp_iState_max[EXTRUDERS];
  115. static bool pid_reset[EXTRUDERS];
  116. #endif //PIDTEMP
  117. #if ENABLED(PIDTEMPBED)
  118. //static cannot be external:
  119. static float temp_iState_bed = { 0 };
  120. static float temp_dState_bed = { 0 };
  121. static float pTerm_bed;
  122. static float iTerm_bed;
  123. static float dTerm_bed;
  124. //int output;
  125. static float pid_error_bed;
  126. static float temp_iState_min_bed;
  127. static float temp_iState_max_bed;
  128. #else //PIDTEMPBED
  129. static millis_t next_bed_check_ms;
  130. #endif //PIDTEMPBED
  131. static unsigned char soft_pwm[EXTRUDERS];
  132. #if ENABLED(FAN_SOFT_PWM)
  133. static unsigned char soft_pwm_fan[FAN_COUNT];
  134. #endif
  135. #if HAS_AUTO_FAN
  136. static millis_t next_auto_fan_check_ms;
  137. #endif
  138. #if ENABLED(PIDTEMP)
  139. #if ENABLED(PID_PARAMS_PER_EXTRUDER)
  140. float Kp[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_Kp);
  141. float Ki[EXTRUDERS] = ARRAY_BY_EXTRUDERS1((DEFAULT_Ki) * (PID_dT));
  142. float Kd[EXTRUDERS] = ARRAY_BY_EXTRUDERS1((DEFAULT_Kd) / (PID_dT));
  143. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  144. float Kc[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_Kc);
  145. #endif // PID_ADD_EXTRUSION_RATE
  146. #else //PID_PARAMS_PER_EXTRUDER
  147. float Kp = DEFAULT_Kp;
  148. float Ki = (DEFAULT_Ki) * (PID_dT);
  149. float Kd = (DEFAULT_Kd) / (PID_dT);
  150. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  151. float Kc = DEFAULT_Kc;
  152. #endif // PID_ADD_EXTRUSION_RATE
  153. #endif // PID_PARAMS_PER_EXTRUDER
  154. #endif //PIDTEMP
  155. // Init min and max temp with extreme values to prevent false errors during startup
  156. static int minttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS(HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP, HEATER_3_RAW_LO_TEMP);
  157. static int maxttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS(HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP, HEATER_3_RAW_HI_TEMP);
  158. static int minttemp[EXTRUDERS] = { 0 };
  159. static int maxttemp[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(16383);
  160. #ifdef BED_MINTEMP
  161. static int bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
  162. #endif
  163. #ifdef BED_MAXTEMP
  164. static int bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
  165. #endif
  166. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  167. static void* heater_ttbl_map[2] = {(void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE };
  168. static uint8_t heater_ttbllen_map[2] = { HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN };
  169. #else
  170. static void* heater_ttbl_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS((void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE, (void*)HEATER_2_TEMPTABLE, (void*)HEATER_3_TEMPTABLE);
  171. static uint8_t heater_ttbllen_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS(HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN, HEATER_3_TEMPTABLE_LEN);
  172. #endif
  173. static float analog2temp(int raw, uint8_t e);
  174. static float analog2tempBed(int raw);
  175. static void updateTemperaturesFromRawValues();
  176. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  177. int watch_target_temp[EXTRUDERS] = { 0 };
  178. millis_t watch_heater_next_ms[EXTRUDERS] = { 0 };
  179. #endif
  180. #ifndef SOFT_PWM_SCALE
  181. #define SOFT_PWM_SCALE 0
  182. #endif
  183. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  184. static int meas_shift_index; //used to point to a delayed sample in buffer for filament width sensor
  185. #endif
  186. #if ENABLED(HEATER_0_USES_MAX6675)
  187. static int read_max6675();
  188. #endif
  189. //===========================================================================
  190. //================================ Functions ================================
  191. //===========================================================================
  192. #if ENABLED(PIDTEMP)
  193. void PID_autotune(float temp, int extruder, int ncycles, bool set_result/*=false*/) {
  194. float input = 0.0;
  195. int cycles = 0;
  196. bool heating = true;
  197. millis_t temp_ms = millis(), t1 = temp_ms, t2 = temp_ms;
  198. long t_high = 0, t_low = 0;
  199. long bias, d;
  200. float Ku, Tu;
  201. float workKp = 0, workKi = 0, workKd = 0;
  202. float max = 0, min = 10000;
  203. #if HAS_AUTO_FAN
  204. millis_t next_auto_fan_check_ms = temp_ms + 2500UL;
  205. #endif
  206. if (extruder >= EXTRUDERS
  207. #if !HAS_TEMP_BED
  208. || extruder < 0
  209. #endif
  210. ) {
  211. SERIAL_ECHOLN(MSG_PID_BAD_EXTRUDER_NUM);
  212. return;
  213. }
  214. SERIAL_ECHOLN(MSG_PID_AUTOTUNE_START);
  215. disable_all_heaters(); // switch off all heaters.
  216. if (extruder < 0)
  217. soft_pwm_bed = bias = d = (MAX_BED_POWER) / 2;
  218. else
  219. soft_pwm[extruder] = bias = d = (PID_MAX) / 2;
  220. // PID Tuning loop
  221. for (;;) {
  222. millis_t ms = millis();
  223. if (temp_meas_ready) { // temp sample ready
  224. updateTemperaturesFromRawValues();
  225. input = (extruder < 0) ? current_temperature_bed : current_temperature[extruder];
  226. max = max(max, input);
  227. min = min(min, input);
  228. #if HAS_AUTO_FAN
  229. if (ELAPSED(ms, next_auto_fan_check_ms)) {
  230. checkExtruderAutoFans();
  231. next_auto_fan_check_ms = ms + 2500UL;
  232. }
  233. #endif
  234. if (heating && input > temp) {
  235. if (ELAPSED(ms, t2 + 5000UL)) {
  236. heating = false;
  237. if (extruder < 0)
  238. soft_pwm_bed = (bias - d) >> 1;
  239. else
  240. soft_pwm[extruder] = (bias - d) >> 1;
  241. t1 = ms;
  242. t_high = t1 - t2;
  243. max = temp;
  244. }
  245. }
  246. if (!heating && input < temp) {
  247. if (ELAPSED(ms, t1 + 5000UL)) {
  248. heating = true;
  249. t2 = ms;
  250. t_low = t2 - t1;
  251. if (cycles > 0) {
  252. long max_pow = extruder < 0 ? MAX_BED_POWER : PID_MAX;
  253. bias += (d * (t_high - t_low)) / (t_low + t_high);
  254. bias = constrain(bias, 20, max_pow - 20);
  255. d = (bias > max_pow / 2) ? max_pow - 1 - bias : bias;
  256. SERIAL_PROTOCOLPGM(MSG_BIAS); SERIAL_PROTOCOL(bias);
  257. SERIAL_PROTOCOLPGM(MSG_D); SERIAL_PROTOCOL(d);
  258. SERIAL_PROTOCOLPGM(MSG_T_MIN); SERIAL_PROTOCOL(min);
  259. SERIAL_PROTOCOLPGM(MSG_T_MAX); SERIAL_PROTOCOLLN(max);
  260. if (cycles > 2) {
  261. Ku = (4.0 * d) / (3.14159265 * (max - min) / 2.0);
  262. Tu = ((float)(t_low + t_high) / 1000.0);
  263. SERIAL_PROTOCOLPGM(MSG_KU); SERIAL_PROTOCOL(Ku);
  264. SERIAL_PROTOCOLPGM(MSG_TU); SERIAL_PROTOCOLLN(Tu);
  265. workKp = 0.6 * Ku;
  266. workKi = 2 * workKp / Tu;
  267. workKd = workKp * Tu / 8;
  268. SERIAL_PROTOCOLLNPGM(MSG_CLASSIC_PID);
  269. SERIAL_PROTOCOLPGM(MSG_KP); SERIAL_PROTOCOLLN(workKp);
  270. SERIAL_PROTOCOLPGM(MSG_KI); SERIAL_PROTOCOLLN(workKi);
  271. SERIAL_PROTOCOLPGM(MSG_KD); SERIAL_PROTOCOLLN(workKd);
  272. /**
  273. workKp = 0.33*Ku;
  274. workKi = workKp/Tu;
  275. workKd = workKp*Tu/3;
  276. SERIAL_PROTOCOLLNPGM(" Some overshoot ");
  277. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(workKp);
  278. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(workKi);
  279. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(workKd);
  280. workKp = 0.2*Ku;
  281. workKi = 2*workKp/Tu;
  282. workKd = workKp*Tu/3;
  283. SERIAL_PROTOCOLLNPGM(" No overshoot ");
  284. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(workKp);
  285. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(workKi);
  286. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(workKd);
  287. */
  288. }
  289. }
  290. if (extruder < 0)
  291. soft_pwm_bed = (bias + d) >> 1;
  292. else
  293. soft_pwm[extruder] = (bias + d) >> 1;
  294. cycles++;
  295. min = temp;
  296. }
  297. }
  298. }
  299. #define MAX_OVERSHOOT_PID_AUTOTUNE 20
  300. if (input > temp + MAX_OVERSHOOT_PID_AUTOTUNE) {
  301. SERIAL_PROTOCOLLNPGM(MSG_PID_TEMP_TOO_HIGH);
  302. return;
  303. }
  304. // Every 2 seconds...
  305. if (ELAPSED(ms, temp_ms + 2000UL)) {
  306. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  307. print_heaterstates();
  308. SERIAL_EOL;
  309. #endif
  310. temp_ms = ms;
  311. } // every 2 seconds
  312. // Over 2 minutes?
  313. if (((ms - t1) + (ms - t2)) > (10L * 60L * 1000L * 2L)) {
  314. SERIAL_PROTOCOLLNPGM(MSG_PID_TIMEOUT);
  315. return;
  316. }
  317. if (cycles > ncycles) {
  318. SERIAL_PROTOCOLLNPGM(MSG_PID_AUTOTUNE_FINISHED);
  319. const char* estring = extruder < 0 ? "bed" : "";
  320. SERIAL_PROTOCOLPGM("#define DEFAULT_"); SERIAL_PROTOCOL(estring); SERIAL_PROTOCOLPGM("Kp "); SERIAL_PROTOCOLLN(workKp);
  321. SERIAL_PROTOCOLPGM("#define DEFAULT_"); SERIAL_PROTOCOL(estring); SERIAL_PROTOCOLPGM("Ki "); SERIAL_PROTOCOLLN(workKi);
  322. SERIAL_PROTOCOLPGM("#define DEFAULT_"); SERIAL_PROTOCOL(estring); SERIAL_PROTOCOLPGM("Kd "); SERIAL_PROTOCOLLN(workKd);
  323. // Use the result? (As with "M303 U1")
  324. if (set_result) {
  325. if (extruder < 0) {
  326. #if ENABLED(PIDTEMPBED)
  327. bedKp = workKp;
  328. bedKi = scalePID_i(workKi);
  329. bedKd = scalePID_d(workKd);
  330. updatePID();
  331. #endif
  332. }
  333. else {
  334. PID_PARAM(Kp, extruder) = workKp;
  335. PID_PARAM(Ki, extruder) = scalePID_i(workKi);
  336. PID_PARAM(Kd, extruder) = scalePID_d(workKd);
  337. updatePID();
  338. }
  339. }
  340. return;
  341. }
  342. lcd_update();
  343. }
  344. }
  345. #endif // PIDTEMP
  346. void updatePID() {
  347. #if ENABLED(PIDTEMP)
  348. for (int e = 0; e < EXTRUDERS; e++) {
  349. temp_iState_max[e] = (PID_INTEGRAL_DRIVE_MAX) / PID_PARAM(Ki, e);
  350. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  351. last_position[e] = 0;
  352. #endif
  353. }
  354. #endif
  355. #if ENABLED(PIDTEMPBED)
  356. temp_iState_max_bed = (PID_BED_INTEGRAL_DRIVE_MAX) / bedKi;
  357. #endif
  358. }
  359. int getHeaterPower(int heater) {
  360. return heater < 0 ? soft_pwm_bed : soft_pwm[heater];
  361. }
  362. #if HAS_AUTO_FAN
  363. void setExtruderAutoFanState(int pin, bool state) {
  364. unsigned char newFanSpeed = (state != 0) ? EXTRUDER_AUTO_FAN_SPEED : 0;
  365. // this idiom allows both digital and PWM fan outputs (see M42 handling).
  366. digitalWrite(pin, newFanSpeed);
  367. analogWrite(pin, newFanSpeed);
  368. }
  369. void checkExtruderAutoFans() {
  370. uint8_t fanState = 0;
  371. // which fan pins need to be turned on?
  372. #if HAS_AUTO_FAN_0
  373. if (current_temperature[0] > EXTRUDER_AUTO_FAN_TEMPERATURE)
  374. fanState |= 1;
  375. #endif
  376. #if HAS_AUTO_FAN_1
  377. if (current_temperature[1] > EXTRUDER_AUTO_FAN_TEMPERATURE) {
  378. if (EXTRUDER_1_AUTO_FAN_PIN == EXTRUDER_0_AUTO_FAN_PIN)
  379. fanState |= 1;
  380. else
  381. fanState |= 2;
  382. }
  383. #endif
  384. #if HAS_AUTO_FAN_2
  385. if (current_temperature[2] > EXTRUDER_AUTO_FAN_TEMPERATURE) {
  386. if (EXTRUDER_2_AUTO_FAN_PIN == EXTRUDER_0_AUTO_FAN_PIN)
  387. fanState |= 1;
  388. else if (EXTRUDER_2_AUTO_FAN_PIN == EXTRUDER_1_AUTO_FAN_PIN)
  389. fanState |= 2;
  390. else
  391. fanState |= 4;
  392. }
  393. #endif
  394. #if HAS_AUTO_FAN_3
  395. if (current_temperature[3] > EXTRUDER_AUTO_FAN_TEMPERATURE) {
  396. if (EXTRUDER_3_AUTO_FAN_PIN == EXTRUDER_0_AUTO_FAN_PIN)
  397. fanState |= 1;
  398. else if (EXTRUDER_3_AUTO_FAN_PIN == EXTRUDER_1_AUTO_FAN_PIN)
  399. fanState |= 2;
  400. else if (EXTRUDER_3_AUTO_FAN_PIN == EXTRUDER_2_AUTO_FAN_PIN)
  401. fanState |= 4;
  402. else
  403. fanState |= 8;
  404. }
  405. #endif
  406. // update extruder auto fan states
  407. #if HAS_AUTO_FAN_0
  408. setExtruderAutoFanState(EXTRUDER_0_AUTO_FAN_PIN, (fanState & 1) != 0);
  409. #endif
  410. #if HAS_AUTO_FAN_1
  411. if (EXTRUDER_1_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN)
  412. setExtruderAutoFanState(EXTRUDER_1_AUTO_FAN_PIN, (fanState & 2) != 0);
  413. #endif
  414. #if HAS_AUTO_FAN_2
  415. if (EXTRUDER_2_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN
  416. && EXTRUDER_2_AUTO_FAN_PIN != EXTRUDER_1_AUTO_FAN_PIN)
  417. setExtruderAutoFanState(EXTRUDER_2_AUTO_FAN_PIN, (fanState & 4) != 0);
  418. #endif
  419. #if HAS_AUTO_FAN_3
  420. if (EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN
  421. && EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_1_AUTO_FAN_PIN
  422. && EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_2_AUTO_FAN_PIN)
  423. setExtruderAutoFanState(EXTRUDER_3_AUTO_FAN_PIN, (fanState & 8) != 0);
  424. #endif
  425. }
  426. #endif // HAS_AUTO_FAN
  427. //
  428. // Temperature Error Handlers
  429. //
  430. inline void _temp_error(int e, const char* serial_msg, const char* lcd_msg) {
  431. static bool killed = false;
  432. if (IsRunning()) {
  433. SERIAL_ERROR_START;
  434. serialprintPGM(serial_msg);
  435. SERIAL_ERRORPGM(MSG_STOPPED_HEATER);
  436. if (e >= 0) SERIAL_ERRORLN((int)e); else SERIAL_ERRORLNPGM(MSG_HEATER_BED);
  437. }
  438. #if DISABLED(BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE)
  439. if (!killed) {
  440. Running = false;
  441. killed = true;
  442. kill(lcd_msg);
  443. }
  444. else
  445. disable_all_heaters(); // paranoia
  446. #endif
  447. }
  448. void max_temp_error(uint8_t e) {
  449. _temp_error(e, PSTR(MSG_T_MAXTEMP), PSTR(MSG_ERR_MAXTEMP));
  450. }
  451. void min_temp_error(uint8_t e) {
  452. _temp_error(e, PSTR(MSG_T_MINTEMP), PSTR(MSG_ERR_MINTEMP));
  453. }
  454. float get_pid_output(int e) {
  455. float pid_output;
  456. #if ENABLED(PIDTEMP)
  457. #if DISABLED(PID_OPENLOOP)
  458. pid_error[e] = target_temperature[e] - current_temperature[e];
  459. dTerm[e] = K2 * PID_PARAM(Kd, e) * (current_temperature[e] - temp_dState[e]) + K1 * dTerm[e];
  460. temp_dState[e] = current_temperature[e];
  461. if (pid_error[e] > PID_FUNCTIONAL_RANGE) {
  462. pid_output = BANG_MAX;
  463. pid_reset[e] = true;
  464. }
  465. else if (pid_error[e] < -(PID_FUNCTIONAL_RANGE) || target_temperature[e] == 0) {
  466. pid_output = 0;
  467. pid_reset[e] = true;
  468. }
  469. else {
  470. if (pid_reset[e]) {
  471. temp_iState[e] = 0.0;
  472. pid_reset[e] = false;
  473. }
  474. pTerm[e] = PID_PARAM(Kp, e) * pid_error[e];
  475. temp_iState[e] += pid_error[e];
  476. temp_iState[e] = constrain(temp_iState[e], temp_iState_min[e], temp_iState_max[e]);
  477. iTerm[e] = PID_PARAM(Ki, e) * temp_iState[e];
  478. pid_output = pTerm[e] + iTerm[e] - dTerm[e];
  479. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  480. cTerm[e] = 0;
  481. if (e == active_extruder) {
  482. long e_position = st_get_position(E_AXIS);
  483. if (e_position > last_position[e]) {
  484. lpq[lpq_ptr++] = e_position - last_position[e];
  485. last_position[e] = e_position;
  486. }
  487. else {
  488. lpq[lpq_ptr++] = 0;
  489. }
  490. if (lpq_ptr >= lpq_len) lpq_ptr = 0;
  491. cTerm[e] = (lpq[lpq_ptr] / axis_steps_per_unit[E_AXIS]) * PID_PARAM(Kc, e);
  492. pid_output += cTerm[e];
  493. }
  494. #endif //PID_ADD_EXTRUSION_RATE
  495. if (pid_output > PID_MAX) {
  496. if (pid_error[e] > 0) temp_iState[e] -= pid_error[e]; // conditional un-integration
  497. pid_output = PID_MAX;
  498. }
  499. else if (pid_output < 0) {
  500. if (pid_error[e] < 0) temp_iState[e] -= pid_error[e]; // conditional un-integration
  501. pid_output = 0;
  502. }
  503. }
  504. #else
  505. pid_output = constrain(target_temperature[e], 0, PID_MAX);
  506. #endif //PID_OPENLOOP
  507. #if ENABLED(PID_DEBUG)
  508. SERIAL_ECHO_START;
  509. SERIAL_ECHOPAIR(MSG_PID_DEBUG, e);
  510. SERIAL_ECHOPAIR(MSG_PID_DEBUG_INPUT, current_temperature[e]);
  511. SERIAL_ECHOPAIR(MSG_PID_DEBUG_OUTPUT, pid_output);
  512. SERIAL_ECHOPAIR(MSG_PID_DEBUG_PTERM, pTerm[e]);
  513. SERIAL_ECHOPAIR(MSG_PID_DEBUG_ITERM, iTerm[e]);
  514. SERIAL_ECHOPAIR(MSG_PID_DEBUG_DTERM, dTerm[e]);
  515. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  516. SERIAL_ECHOPAIR(MSG_PID_DEBUG_CTERM, cTerm[e]);
  517. #endif
  518. SERIAL_EOL;
  519. #endif //PID_DEBUG
  520. #else /* PID off */
  521. pid_output = (current_temperature[e] < target_temperature[e]) ? PID_MAX : 0;
  522. #endif
  523. return pid_output;
  524. }
  525. #if ENABLED(PIDTEMPBED)
  526. float get_pid_output_bed() {
  527. float pid_output;
  528. #if DISABLED(PID_OPENLOOP)
  529. pid_error_bed = target_temperature_bed - current_temperature_bed;
  530. pTerm_bed = bedKp * pid_error_bed;
  531. temp_iState_bed += pid_error_bed;
  532. temp_iState_bed = constrain(temp_iState_bed, temp_iState_min_bed, temp_iState_max_bed);
  533. iTerm_bed = bedKi * temp_iState_bed;
  534. dTerm_bed = K2 * bedKd * (current_temperature_bed - temp_dState_bed) + K1 * dTerm_bed;
  535. temp_dState_bed = current_temperature_bed;
  536. pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
  537. if (pid_output > MAX_BED_POWER) {
  538. if (pid_error_bed > 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
  539. pid_output = MAX_BED_POWER;
  540. }
  541. else if (pid_output < 0) {
  542. if (pid_error_bed < 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
  543. pid_output = 0;
  544. }
  545. #else
  546. pid_output = constrain(target_temperature_bed, 0, MAX_BED_POWER);
  547. #endif // PID_OPENLOOP
  548. #if ENABLED(PID_BED_DEBUG)
  549. SERIAL_ECHO_START;
  550. SERIAL_ECHO(" PID_BED_DEBUG ");
  551. SERIAL_ECHO(": Input ");
  552. SERIAL_ECHO(current_temperature_bed);
  553. SERIAL_ECHO(" Output ");
  554. SERIAL_ECHO(pid_output);
  555. SERIAL_ECHO(" pTerm ");
  556. SERIAL_ECHO(pTerm_bed);
  557. SERIAL_ECHO(" iTerm ");
  558. SERIAL_ECHO(iTerm_bed);
  559. SERIAL_ECHO(" dTerm ");
  560. SERIAL_ECHOLN(dTerm_bed);
  561. #endif //PID_BED_DEBUG
  562. return pid_output;
  563. }
  564. #endif //PIDTEMPBED
  565. /**
  566. * Manage heating activities for extruder hot-ends and a heated bed
  567. * - Acquire updated temperature readings
  568. * - Invoke thermal runaway protection
  569. * - Manage extruder auto-fan
  570. * - Apply filament width to the extrusion rate (may move)
  571. * - Update the heated bed PID output value
  572. */
  573. void manage_heater() {
  574. if (!temp_meas_ready) return;
  575. updateTemperaturesFromRawValues();
  576. #if ENABLED(HEATER_0_USES_MAX6675)
  577. float ct = current_temperature[0];
  578. if (ct > min(HEATER_0_MAXTEMP, 1023)) max_temp_error(0);
  579. if (ct < max(HEATER_0_MINTEMP, 0.01)) min_temp_error(0);
  580. #endif
  581. #if ENABLED(THERMAL_PROTECTION_HOTENDS) || DISABLED(PIDTEMPBED) || HAS_AUTO_FAN
  582. millis_t ms = millis();
  583. #endif
  584. // Loop through all extruders
  585. for (int e = 0; e < EXTRUDERS; e++) {
  586. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  587. 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);
  588. #endif
  589. float pid_output = get_pid_output(e);
  590. // Check if temperature is within the correct range
  591. soft_pwm[e] = current_temperature[e] > minttemp[e] && current_temperature[e] < maxttemp[e] ? (int)pid_output >> 1 : 0;
  592. // Check if the temperature is failing to increase
  593. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  594. // Is it time to check this extruder's heater?
  595. if (watch_heater_next_ms[e] && ELAPSED(ms, watch_heater_next_ms[e])) {
  596. // Has it failed to increase enough?
  597. if (degHotend(e) < watch_target_temp[e]) {
  598. // Stop!
  599. _temp_error(e, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
  600. }
  601. else {
  602. // Start again if the target is still far off
  603. start_watching_heater(e);
  604. }
  605. }
  606. #endif // THERMAL_PROTECTION_HOTENDS
  607. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  608. if (fabs(current_temperature[0] - redundant_temperature) > MAX_REDUNDANT_TEMP_SENSOR_DIFF) {
  609. _temp_error(0, PSTR(MSG_REDUNDANCY), PSTR(MSG_ERR_REDUNDANT_TEMP));
  610. }
  611. #endif
  612. } // Extruders Loop
  613. #if HAS_AUTO_FAN
  614. if (ELAPSED(ms, next_auto_fan_check_ms)) { // only need to check fan state very infrequently
  615. checkExtruderAutoFans();
  616. next_auto_fan_check_ms = ms + 2500UL;
  617. }
  618. #endif
  619. // Control the extruder rate based on the width sensor
  620. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  621. if (filament_sensor) {
  622. meas_shift_index = filwidth_delay_index1 - meas_delay_cm;
  623. if (meas_shift_index < 0) meas_shift_index += MAX_MEASUREMENT_DELAY + 1; //loop around buffer if needed
  624. // Get the delayed info and add 100 to reconstitute to a percent of
  625. // the nominal filament diameter then square it to get an area
  626. meas_shift_index = constrain(meas_shift_index, 0, MAX_MEASUREMENT_DELAY);
  627. float vm = pow((measurement_delay[meas_shift_index] + 100.0) / 100.0, 2);
  628. NOLESS(vm, 0.01);
  629. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = vm;
  630. }
  631. #endif //FILAMENT_WIDTH_SENSOR
  632. #if DISABLED(PIDTEMPBED)
  633. if (PENDING(ms, next_bed_check_ms)) return;
  634. next_bed_check_ms = ms + BED_CHECK_INTERVAL;
  635. #endif
  636. #if TEMP_SENSOR_BED != 0
  637. #if ENABLED(THERMAL_PROTECTION_BED)
  638. 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);
  639. #endif
  640. #if ENABLED(PIDTEMPBED)
  641. float pid_output = get_pid_output_bed();
  642. soft_pwm_bed = current_temperature_bed > BED_MINTEMP && current_temperature_bed < BED_MAXTEMP ? (int)pid_output >> 1 : 0;
  643. #elif ENABLED(BED_LIMIT_SWITCHING)
  644. // Check if temperature is within the correct band
  645. if (current_temperature_bed > BED_MINTEMP && current_temperature_bed < BED_MAXTEMP) {
  646. if (current_temperature_bed >= target_temperature_bed + BED_HYSTERESIS)
  647. soft_pwm_bed = 0;
  648. else if (current_temperature_bed <= target_temperature_bed - (BED_HYSTERESIS))
  649. soft_pwm_bed = MAX_BED_POWER >> 1;
  650. }
  651. else {
  652. soft_pwm_bed = 0;
  653. WRITE_HEATER_BED(LOW);
  654. }
  655. #else // !PIDTEMPBED && !BED_LIMIT_SWITCHING
  656. // Check if temperature is within the correct range
  657. if (current_temperature_bed > BED_MINTEMP && current_temperature_bed < BED_MAXTEMP) {
  658. soft_pwm_bed = current_temperature_bed < target_temperature_bed ? MAX_BED_POWER >> 1 : 0;
  659. }
  660. else {
  661. soft_pwm_bed = 0;
  662. WRITE_HEATER_BED(LOW);
  663. }
  664. #endif
  665. #endif //TEMP_SENSOR_BED != 0
  666. }
  667. #define PGM_RD_W(x) (short)pgm_read_word(&x)
  668. // Derived from RepRap FiveD extruder::getTemperature()
  669. // For hot end temperature measurement.
  670. static float analog2temp(int raw, uint8_t e) {
  671. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  672. if (e > EXTRUDERS)
  673. #else
  674. if (e >= EXTRUDERS)
  675. #endif
  676. {
  677. SERIAL_ERROR_START;
  678. SERIAL_ERROR((int)e);
  679. SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER_NUM);
  680. kill(PSTR(MSG_KILLED));
  681. return 0.0;
  682. }
  683. #if ENABLED(HEATER_0_USES_MAX6675)
  684. if (e == 0) return 0.25 * raw;
  685. #endif
  686. if (heater_ttbl_map[e] != NULL) {
  687. float celsius = 0;
  688. uint8_t i;
  689. short(*tt)[][2] = (short(*)[][2])(heater_ttbl_map[e]);
  690. for (i = 1; i < heater_ttbllen_map[e]; i++) {
  691. if (PGM_RD_W((*tt)[i][0]) > raw) {
  692. celsius = PGM_RD_W((*tt)[i - 1][1]) +
  693. (raw - PGM_RD_W((*tt)[i - 1][0])) *
  694. (float)(PGM_RD_W((*tt)[i][1]) - PGM_RD_W((*tt)[i - 1][1])) /
  695. (float)(PGM_RD_W((*tt)[i][0]) - PGM_RD_W((*tt)[i - 1][0]));
  696. break;
  697. }
  698. }
  699. // Overflow: Set to last value in the table
  700. if (i == heater_ttbllen_map[e]) celsius = PGM_RD_W((*tt)[i - 1][1]);
  701. return celsius;
  702. }
  703. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
  704. }
  705. // Derived from RepRap FiveD extruder::getTemperature()
  706. // For bed temperature measurement.
  707. static float analog2tempBed(int raw) {
  708. #if ENABLED(BED_USES_THERMISTOR)
  709. float celsius = 0;
  710. byte i;
  711. for (i = 1; i < BEDTEMPTABLE_LEN; i++) {
  712. if (PGM_RD_W(BEDTEMPTABLE[i][0]) > raw) {
  713. celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]) +
  714. (raw - PGM_RD_W(BEDTEMPTABLE[i - 1][0])) *
  715. (float)(PGM_RD_W(BEDTEMPTABLE[i][1]) - PGM_RD_W(BEDTEMPTABLE[i - 1][1])) /
  716. (float)(PGM_RD_W(BEDTEMPTABLE[i][0]) - PGM_RD_W(BEDTEMPTABLE[i - 1][0]));
  717. break;
  718. }
  719. }
  720. // Overflow: Set to last value in the table
  721. if (i == BEDTEMPTABLE_LEN) celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]);
  722. return celsius;
  723. #elif defined(BED_USES_AD595)
  724. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
  725. #else
  726. UNUSED(raw);
  727. return 0;
  728. #endif
  729. }
  730. /* Called to get the raw values into the the actual temperatures. The raw values are created in interrupt context,
  731. and this function is called from normal context as it is too slow to run in interrupts and will block the stepper routine otherwise */
  732. static void updateTemperaturesFromRawValues() {
  733. #if ENABLED(HEATER_0_USES_MAX6675)
  734. current_temperature_raw[0] = read_max6675();
  735. #endif
  736. for (uint8_t e = 0; e < EXTRUDERS; e++) {
  737. current_temperature[e] = analog2temp(current_temperature_raw[e], e);
  738. }
  739. current_temperature_bed = analog2tempBed(current_temperature_bed_raw);
  740. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  741. redundant_temperature = analog2temp(redundant_temperature_raw, 1);
  742. #endif
  743. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  744. filament_width_meas = analog2widthFil();
  745. #endif
  746. #if ENABLED(USE_WATCHDOG)
  747. // Reset the watchdog after we know we have a temperature measurement.
  748. watchdog_reset();
  749. #endif
  750. CRITICAL_SECTION_START;
  751. temp_meas_ready = false;
  752. CRITICAL_SECTION_END;
  753. }
  754. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  755. // Convert raw Filament Width to millimeters
  756. float analog2widthFil() {
  757. return current_raw_filwidth / 16383.0 * 5.0;
  758. //return current_raw_filwidth;
  759. }
  760. // Convert raw Filament Width to a ratio
  761. int widthFil_to_size_ratio() {
  762. float temp = filament_width_meas;
  763. if (temp < MEASURED_LOWER_LIMIT) temp = filament_width_nominal; //assume sensor cut out
  764. else NOMORE(temp, MEASURED_UPPER_LIMIT);
  765. return filament_width_nominal / temp * 100;
  766. }
  767. #endif
  768. /**
  769. * Initialize the temperature manager
  770. * The manager is implemented by periodic calls to manage_heater()
  771. */
  772. void tp_init() {
  773. #if MB(RUMBA) && ((TEMP_SENSOR_0==-1)||(TEMP_SENSOR_1==-1)||(TEMP_SENSOR_2==-1)||(TEMP_SENSOR_BED==-1))
  774. //disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
  775. MCUCR = _BV(JTD);
  776. MCUCR = _BV(JTD);
  777. #endif
  778. // Finish init of mult extruder arrays
  779. for (int e = 0; e < EXTRUDERS; e++) {
  780. // populate with the first value
  781. maxttemp[e] = maxttemp[0];
  782. #if ENABLED(PIDTEMP)
  783. temp_iState_min[e] = 0.0;
  784. temp_iState_max[e] = (PID_INTEGRAL_DRIVE_MAX) / PID_PARAM(Ki, e);
  785. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  786. last_position[e] = 0;
  787. #endif
  788. #endif //PIDTEMP
  789. #if ENABLED(PIDTEMPBED)
  790. temp_iState_min_bed = 0.0;
  791. temp_iState_max_bed = (PID_BED_INTEGRAL_DRIVE_MAX) / bedKi;
  792. #endif //PIDTEMPBED
  793. }
  794. #if HAS_HEATER_0
  795. SET_OUTPUT(HEATER_0_PIN);
  796. #endif
  797. #if HAS_HEATER_1
  798. SET_OUTPUT(HEATER_1_PIN);
  799. #endif
  800. #if HAS_HEATER_2
  801. SET_OUTPUT(HEATER_2_PIN);
  802. #endif
  803. #if HAS_HEATER_3
  804. SET_OUTPUT(HEATER_3_PIN);
  805. #endif
  806. #if HAS_HEATER_BED
  807. SET_OUTPUT(HEATER_BED_PIN);
  808. #endif
  809. #if ENABLED(FAST_PWM_FAN) || ENABLED(FAN_SOFT_PWM)
  810. #if HAS_FAN0
  811. SET_OUTPUT(FAN_PIN);
  812. #if ENABLED(FAST_PWM_FAN)
  813. setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  814. #endif
  815. #if ENABLED(FAN_SOFT_PWM)
  816. soft_pwm_fan[0] = fanSpeedSoftPwm[0] / 2;
  817. #endif
  818. #endif
  819. #if HAS_FAN1
  820. SET_OUTPUT(FAN1_PIN);
  821. #if ENABLED(FAST_PWM_FAN)
  822. setPwmFrequency(FAN1_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  823. #endif
  824. #if ENABLED(FAN_SOFT_PWM)
  825. soft_pwm_fan[1] = fanSpeedSoftPwm[1] / 2;
  826. #endif
  827. #endif
  828. #if HAS_FAN2
  829. SET_OUTPUT(FAN2_PIN);
  830. #if ENABLED(FAST_PWM_FAN)
  831. setPwmFrequency(FAN2_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  832. #endif
  833. #if ENABLED(FAN_SOFT_PWM)
  834. soft_pwm_fan[2] = fanSpeedSoftPwm[2] / 2;
  835. #endif
  836. #endif
  837. #endif // FAST_PWM_FAN || FAN_SOFT_PWM
  838. #if ENABLED(HEATER_0_USES_MAX6675)
  839. #if DISABLED(SDSUPPORT)
  840. OUT_WRITE(SCK_PIN, LOW);
  841. OUT_WRITE(MOSI_PIN, HIGH);
  842. OUT_WRITE(MISO_PIN, HIGH);
  843. #else
  844. pinMode(SS_PIN, OUTPUT);
  845. digitalWrite(SS_PIN, HIGH);
  846. #endif
  847. OUT_WRITE(MAX6675_SS, HIGH);
  848. #endif //HEATER_0_USES_MAX6675
  849. #ifdef DIDR2
  850. #define ANALOG_SELECT(pin) do{ if (pin < 8) SBI(DIDR0, pin); else SBI(DIDR2, pin - 8); }while(0)
  851. #else
  852. #define ANALOG_SELECT(pin) do{ SBI(DIDR0, pin); }while(0)
  853. #endif
  854. // Set analog inputs
  855. ADCSRA = _BV(ADEN) | _BV(ADSC) | _BV(ADIF) | 0x07;
  856. DIDR0 = 0;
  857. #ifdef DIDR2
  858. DIDR2 = 0;
  859. #endif
  860. #if HAS_TEMP_0
  861. ANALOG_SELECT(TEMP_0_PIN);
  862. #endif
  863. #if HAS_TEMP_1
  864. ANALOG_SELECT(TEMP_1_PIN);
  865. #endif
  866. #if HAS_TEMP_2
  867. ANALOG_SELECT(TEMP_2_PIN);
  868. #endif
  869. #if HAS_TEMP_3
  870. ANALOG_SELECT(TEMP_3_PIN);
  871. #endif
  872. #if HAS_TEMP_BED
  873. ANALOG_SELECT(TEMP_BED_PIN);
  874. #endif
  875. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  876. ANALOG_SELECT(FILWIDTH_PIN);
  877. #endif
  878. #if HAS_AUTO_FAN_0
  879. pinMode(EXTRUDER_0_AUTO_FAN_PIN, OUTPUT);
  880. #endif
  881. #if HAS_AUTO_FAN_1 && (EXTRUDER_1_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN)
  882. pinMode(EXTRUDER_1_AUTO_FAN_PIN, OUTPUT);
  883. #endif
  884. #if HAS_AUTO_FAN_2 && (EXTRUDER_2_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN) && (EXTRUDER_2_AUTO_FAN_PIN != EXTRUDER_1_AUTO_FAN_PIN)
  885. pinMode(EXTRUDER_2_AUTO_FAN_PIN, OUTPUT);
  886. #endif
  887. #if HAS_AUTO_FAN_3 && (EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_0_AUTO_FAN_PIN) && (EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_1_AUTO_FAN_PIN) && (EXTRUDER_3_AUTO_FAN_PIN != EXTRUDER_2_AUTO_FAN_PIN)
  888. pinMode(EXTRUDER_3_AUTO_FAN_PIN, OUTPUT);
  889. #endif
  890. // Use timer0 for temperature measurement
  891. // Interleave temperature interrupt with millies interrupt
  892. OCR0B = 128;
  893. SBI(TIMSK0, OCIE0B);
  894. // Wait for temperature measurement to settle
  895. delay(250);
  896. #define TEMP_MIN_ROUTINE(NR) \
  897. minttemp[NR] = HEATER_ ## NR ## _MINTEMP; \
  898. while(analog2temp(minttemp_raw[NR], NR) < HEATER_ ## NR ## _MINTEMP) { \
  899. if (HEATER_ ## NR ## _RAW_LO_TEMP < HEATER_ ## NR ## _RAW_HI_TEMP) \
  900. minttemp_raw[NR] += OVERSAMPLENR; \
  901. else \
  902. minttemp_raw[NR] -= OVERSAMPLENR; \
  903. }
  904. #define TEMP_MAX_ROUTINE(NR) \
  905. maxttemp[NR] = HEATER_ ## NR ## _MAXTEMP; \
  906. while(analog2temp(maxttemp_raw[NR], NR) > HEATER_ ## NR ## _MAXTEMP) { \
  907. if (HEATER_ ## NR ## _RAW_LO_TEMP < HEATER_ ## NR ## _RAW_HI_TEMP) \
  908. maxttemp_raw[NR] -= OVERSAMPLENR; \
  909. else \
  910. maxttemp_raw[NR] += OVERSAMPLENR; \
  911. }
  912. #ifdef HEATER_0_MINTEMP
  913. TEMP_MIN_ROUTINE(0);
  914. #endif
  915. #ifdef HEATER_0_MAXTEMP
  916. TEMP_MAX_ROUTINE(0);
  917. #endif
  918. #if EXTRUDERS > 1
  919. #ifdef HEATER_1_MINTEMP
  920. TEMP_MIN_ROUTINE(1);
  921. #endif
  922. #ifdef HEATER_1_MAXTEMP
  923. TEMP_MAX_ROUTINE(1);
  924. #endif
  925. #if EXTRUDERS > 2
  926. #ifdef HEATER_2_MINTEMP
  927. TEMP_MIN_ROUTINE(2);
  928. #endif
  929. #ifdef HEATER_2_MAXTEMP
  930. TEMP_MAX_ROUTINE(2);
  931. #endif
  932. #if EXTRUDERS > 3
  933. #ifdef HEATER_3_MINTEMP
  934. TEMP_MIN_ROUTINE(3);
  935. #endif
  936. #ifdef HEATER_3_MAXTEMP
  937. TEMP_MAX_ROUTINE(3);
  938. #endif
  939. #endif // EXTRUDERS > 3
  940. #endif // EXTRUDERS > 2
  941. #endif // EXTRUDERS > 1
  942. #ifdef BED_MINTEMP
  943. while(analog2tempBed(bed_minttemp_raw) < BED_MINTEMP) {
  944. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  945. bed_minttemp_raw += OVERSAMPLENR;
  946. #else
  947. bed_minttemp_raw -= OVERSAMPLENR;
  948. #endif
  949. }
  950. #endif //BED_MINTEMP
  951. #ifdef BED_MAXTEMP
  952. while (analog2tempBed(bed_maxttemp_raw) > BED_MAXTEMP) {
  953. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  954. bed_maxttemp_raw -= OVERSAMPLENR;
  955. #else
  956. bed_maxttemp_raw += OVERSAMPLENR;
  957. #endif
  958. }
  959. #endif //BED_MAXTEMP
  960. }
  961. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  962. /**
  963. * Start Heating Sanity Check for hotends that are below
  964. * their target temperature by a configurable margin.
  965. * This is called when the temperature is set. (M104, M109)
  966. */
  967. void start_watching_heater(int e) {
  968. if (degHotend(e) < degTargetHotend(e) - (WATCH_TEMP_INCREASE + TEMP_HYSTERESIS + 1)) {
  969. watch_target_temp[e] = degHotend(e) + WATCH_TEMP_INCREASE;
  970. watch_heater_next_ms[e] = millis() + (WATCH_TEMP_PERIOD) * 1000UL;
  971. }
  972. else
  973. watch_heater_next_ms[e] = 0;
  974. }
  975. #endif
  976. #if ENABLED(THERMAL_PROTECTION_HOTENDS) || ENABLED(THERMAL_PROTECTION_BED)
  977. void thermal_runaway_protection(TRState* state, millis_t* timer, float temperature, float target_temperature, int heater_id, int period_seconds, int hysteresis_degc) {
  978. static float tr_target_temperature[EXTRUDERS + 1] = { 0.0 };
  979. /**
  980. SERIAL_ECHO_START;
  981. SERIAL_ECHOPGM("Thermal Thermal Runaway Running. Heater ID: ");
  982. if (heater_id < 0) SERIAL_ECHOPGM("bed"); else SERIAL_ECHOPGM(heater_id);
  983. SERIAL_ECHOPGM(" ; State:");
  984. SERIAL_ECHOPGM(*state);
  985. SERIAL_ECHOPGM(" ; Timer:");
  986. SERIAL_ECHOPGM(*timer);
  987. SERIAL_ECHOPGM(" ; Temperature:");
  988. SERIAL_ECHOPGM(temperature);
  989. SERIAL_ECHOPGM(" ; Target Temp:");
  990. SERIAL_ECHOPGM(target_temperature);
  991. SERIAL_EOL;
  992. */
  993. int heater_index = heater_id >= 0 ? heater_id : EXTRUDERS;
  994. // If the target temperature changes, restart
  995. if (tr_target_temperature[heater_index] != target_temperature)
  996. *state = TRReset;
  997. switch (*state) {
  998. case TRReset:
  999. *timer = 0;
  1000. *state = TRInactive;
  1001. // Inactive state waits for a target temperature to be set
  1002. case TRInactive:
  1003. if (target_temperature > 0) {
  1004. tr_target_temperature[heater_index] = target_temperature;
  1005. *state = TRFirstHeating;
  1006. }
  1007. break;
  1008. // When first heating, wait for the temperature to be reached then go to Stable state
  1009. case TRFirstHeating:
  1010. if (temperature >= tr_target_temperature[heater_index]) *state = TRStable;
  1011. break;
  1012. // While the temperature is stable watch for a bad temperature
  1013. case TRStable:
  1014. // If the temperature is over the target (-hysteresis) restart the timer
  1015. if (temperature >= tr_target_temperature[heater_index] - hysteresis_degc)
  1016. *timer = millis();
  1017. // If the timer goes too long without a reset, trigger shutdown
  1018. else if (ELAPSED(millis(), *timer + period_seconds * 1000UL))
  1019. *state = TRRunaway;
  1020. break;
  1021. case TRRunaway:
  1022. _temp_error(heater_id, PSTR(MSG_T_THERMAL_RUNAWAY), PSTR(MSG_THERMAL_RUNAWAY));
  1023. }
  1024. }
  1025. #endif // THERMAL_PROTECTION_HOTENDS || THERMAL_PROTECTION_BED
  1026. void disable_all_heaters() {
  1027. for (int i = 0; i < EXTRUDERS; i++) setTargetHotend(0, i);
  1028. setTargetBed(0);
  1029. // If all heaters go down then for sure our print job has stopped
  1030. print_job_timer.stop();
  1031. #define DISABLE_HEATER(NR) { \
  1032. setTargetHotend(NR, 0); \
  1033. soft_pwm[NR] = 0; \
  1034. WRITE_HEATER_ ## NR (LOW); \
  1035. }
  1036. #if HAS_TEMP_HOTEND
  1037. setTargetHotend(0, 0);
  1038. soft_pwm[0] = 0;
  1039. WRITE_HEATER_0P(LOW); // Should HEATERS_PARALLEL apply here? Then change to DISABLE_HEATER(0)
  1040. #endif
  1041. #if EXTRUDERS > 1 && HAS_TEMP_1
  1042. DISABLE_HEATER(1);
  1043. #endif
  1044. #if EXTRUDERS > 2 && HAS_TEMP_2
  1045. DISABLE_HEATER(2);
  1046. #endif
  1047. #if EXTRUDERS > 3 && HAS_TEMP_3
  1048. DISABLE_HEATER(3);
  1049. #endif
  1050. #if HAS_TEMP_BED
  1051. target_temperature_bed = 0;
  1052. soft_pwm_bed = 0;
  1053. #if HAS_HEATER_BED
  1054. WRITE_HEATER_BED(LOW);
  1055. #endif
  1056. #endif
  1057. }
  1058. #if ENABLED(HEATER_0_USES_MAX6675)
  1059. #define MAX6675_HEAT_INTERVAL 250u
  1060. #if ENABLED(MAX6675_IS_MAX31855)
  1061. uint32_t max6675_temp = 2000;
  1062. #define MAX6675_ERROR_MASK 7
  1063. #define MAX6675_DISCARD_BITS 18
  1064. #else
  1065. uint16_t max6675_temp = 2000;
  1066. #define MAX6675_ERROR_MASK 4
  1067. #define MAX6675_DISCARD_BITS 3
  1068. #endif
  1069. static millis_t next_max6675_ms = 0;
  1070. static int read_max6675() {
  1071. millis_t ms = millis();
  1072. if (PENDING(ms, next_max6675_ms)) return (int)max6675_temp;
  1073. next_max6675_ms = ms + MAX6675_HEAT_INTERVAL;
  1074. CBI(
  1075. #ifdef PRR
  1076. PRR
  1077. #elif defined(PRR0)
  1078. PRR0
  1079. #endif
  1080. , PRSPI);
  1081. SPCR = _BV(MSTR) | _BV(SPE) | _BV(SPR0);
  1082. WRITE(MAX6675_SS, 0); // enable TT_MAX6675
  1083. // ensure 100ns delay - a bit extra is fine
  1084. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1085. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1086. // Read a big-endian temperature value
  1087. max6675_temp = 0;
  1088. for (uint8_t i = sizeof(max6675_temp); i--;) {
  1089. SPDR = 0;
  1090. for (;!TEST(SPSR, SPIF););
  1091. max6675_temp |= SPDR;
  1092. if (i > 0) max6675_temp <<= 8; // shift left if not the last byte
  1093. }
  1094. WRITE(MAX6675_SS, 1); // disable TT_MAX6675
  1095. if (max6675_temp & MAX6675_ERROR_MASK)
  1096. max6675_temp = 4000; // thermocouple open
  1097. else
  1098. max6675_temp >>= MAX6675_DISCARD_BITS;
  1099. return (int)max6675_temp;
  1100. }
  1101. #endif //HEATER_0_USES_MAX6675
  1102. /**
  1103. * Stages in the ISR loop
  1104. */
  1105. enum TempState {
  1106. PrepareTemp_0,
  1107. MeasureTemp_0,
  1108. PrepareTemp_BED,
  1109. MeasureTemp_BED,
  1110. PrepareTemp_1,
  1111. MeasureTemp_1,
  1112. PrepareTemp_2,
  1113. MeasureTemp_2,
  1114. PrepareTemp_3,
  1115. MeasureTemp_3,
  1116. Prepare_FILWIDTH,
  1117. Measure_FILWIDTH,
  1118. StartupDelay // Startup, delay initial temp reading a tiny bit so the hardware can settle
  1119. };
  1120. static unsigned long raw_temp_value[4] = { 0 };
  1121. static unsigned long raw_temp_bed_value = 0;
  1122. static void set_current_temp_raw() {
  1123. #if HAS_TEMP_0 && DISABLED(HEATER_0_USES_MAX6675)
  1124. current_temperature_raw[0] = raw_temp_value[0];
  1125. #endif
  1126. #if HAS_TEMP_1
  1127. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  1128. redundant_temperature_raw = raw_temp_value[1];
  1129. #else
  1130. current_temperature_raw[1] = raw_temp_value[1];
  1131. #endif
  1132. #if HAS_TEMP_2
  1133. current_temperature_raw[2] = raw_temp_value[2];
  1134. #if HAS_TEMP_3
  1135. current_temperature_raw[3] = raw_temp_value[3];
  1136. #endif
  1137. #endif
  1138. #endif
  1139. current_temperature_bed_raw = raw_temp_bed_value;
  1140. temp_meas_ready = true;
  1141. }
  1142. /**
  1143. * Timer 0 is shared with millies
  1144. * - Manage PWM to all the heaters and fan
  1145. * - Update the raw temperature values
  1146. * - Check new temperature values for MIN/MAX errors
  1147. * - Step the babysteps value for each axis towards 0
  1148. */
  1149. ISR(TIMER0_COMPB_vect) {
  1150. static unsigned char temp_count = 0;
  1151. static TempState temp_state = StartupDelay;
  1152. static unsigned char pwm_count = _BV(SOFT_PWM_SCALE);
  1153. // Static members for each heater
  1154. #if ENABLED(SLOW_PWM_HEATERS)
  1155. static unsigned char slow_pwm_count = 0;
  1156. #define ISR_STATICS(n) \
  1157. static unsigned char soft_pwm_ ## n; \
  1158. static unsigned char state_heater_ ## n = 0; \
  1159. static unsigned char state_timer_heater_ ## n = 0
  1160. #else
  1161. #define ISR_STATICS(n) static unsigned char soft_pwm_ ## n
  1162. #endif
  1163. // Statics per heater
  1164. ISR_STATICS(0);
  1165. #if (EXTRUDERS > 1) || ENABLED(HEATERS_PARALLEL)
  1166. ISR_STATICS(1);
  1167. #if EXTRUDERS > 2
  1168. ISR_STATICS(2);
  1169. #if EXTRUDERS > 3
  1170. ISR_STATICS(3);
  1171. #endif
  1172. #endif
  1173. #endif
  1174. #if HAS_HEATER_BED
  1175. ISR_STATICS(BED);
  1176. #endif
  1177. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1178. static unsigned long raw_filwidth_value = 0;
  1179. #endif
  1180. #if DISABLED(SLOW_PWM_HEATERS)
  1181. /**
  1182. * standard PWM modulation
  1183. */
  1184. if (pwm_count == 0) {
  1185. soft_pwm_0 = soft_pwm[0];
  1186. if (soft_pwm_0 > 0) {
  1187. WRITE_HEATER_0(1);
  1188. }
  1189. else WRITE_HEATER_0P(0); // If HEATERS_PARALLEL should apply, change to WRITE_HEATER_0
  1190. #if EXTRUDERS > 1
  1191. soft_pwm_1 = soft_pwm[1];
  1192. WRITE_HEATER_1(soft_pwm_1 > 0 ? 1 : 0);
  1193. #if EXTRUDERS > 2
  1194. soft_pwm_2 = soft_pwm[2];
  1195. WRITE_HEATER_2(soft_pwm_2 > 0 ? 1 : 0);
  1196. #if EXTRUDERS > 3
  1197. soft_pwm_3 = soft_pwm[3];
  1198. WRITE_HEATER_3(soft_pwm_3 > 0 ? 1 : 0);
  1199. #endif
  1200. #endif
  1201. #endif
  1202. #if HAS_HEATER_BED
  1203. soft_pwm_BED = soft_pwm_bed;
  1204. WRITE_HEATER_BED(soft_pwm_BED > 0 ? 1 : 0);
  1205. #endif
  1206. #if ENABLED(FAN_SOFT_PWM)
  1207. #if HAS_FAN0
  1208. soft_pwm_fan[0] = fanSpeedSoftPwm[0] / 2;
  1209. WRITE_FAN(soft_pwm_fan[0] > 0 ? 1 : 0);
  1210. #endif
  1211. #if HAS_FAN1
  1212. soft_pwm_fan[1] = fanSpeedSoftPwm[1] / 2;
  1213. WRITE_FAN1(soft_pwm_fan[1] > 0 ? 1 : 0);
  1214. #endif
  1215. #if HAS_FAN2
  1216. soft_pwm_fan[2] = fanSpeedSoftPwm[2] / 2;
  1217. WRITE_FAN2(soft_pwm_fan[2] > 0 ? 1 : 0);
  1218. #endif
  1219. #endif
  1220. }
  1221. if (soft_pwm_0 < pwm_count) WRITE_HEATER_0(0);
  1222. #if EXTRUDERS > 1
  1223. if (soft_pwm_1 < pwm_count) WRITE_HEATER_1(0);
  1224. #if EXTRUDERS > 2
  1225. if (soft_pwm_2 < pwm_count) WRITE_HEATER_2(0);
  1226. #if EXTRUDERS > 3
  1227. if (soft_pwm_3 < pwm_count) WRITE_HEATER_3(0);
  1228. #endif
  1229. #endif
  1230. #endif
  1231. #if HAS_HEATER_BED
  1232. if (soft_pwm_BED < pwm_count) WRITE_HEATER_BED(0);
  1233. #endif
  1234. #if ENABLED(FAN_SOFT_PWM)
  1235. #if HAS_FAN0
  1236. if (soft_pwm_fan[0] < pwm_count) WRITE_FAN(0);
  1237. #endif
  1238. #if HAS_FAN1
  1239. if (soft_pwm_fan[1] < pwm_count) WRITE_FAN1(0);
  1240. #endif
  1241. #if HAS_FAN2
  1242. if (soft_pwm_fan[2] < pwm_count) WRITE_FAN2(0);
  1243. #endif
  1244. #endif
  1245. pwm_count += _BV(SOFT_PWM_SCALE);
  1246. pwm_count &= 0x7f;
  1247. #else // SLOW_PWM_HEATERS
  1248. /**
  1249. * SLOW PWM HEATERS
  1250. *
  1251. * for heaters drived by relay
  1252. */
  1253. #ifndef MIN_STATE_TIME
  1254. #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
  1255. #endif
  1256. // Macros for Slow PWM timer logic - HEATERS_PARALLEL applies
  1257. #define _SLOW_PWM_ROUTINE(NR, src) \
  1258. soft_pwm_ ## NR = src; \
  1259. if (soft_pwm_ ## NR > 0) { \
  1260. if (state_timer_heater_ ## NR == 0) { \
  1261. if (state_heater_ ## NR == 0) state_timer_heater_ ## NR = MIN_STATE_TIME; \
  1262. state_heater_ ## NR = 1; \
  1263. WRITE_HEATER_ ## NR(1); \
  1264. } \
  1265. } \
  1266. else { \
  1267. if (state_timer_heater_ ## NR == 0) { \
  1268. if (state_heater_ ## NR == 1) state_timer_heater_ ## NR = MIN_STATE_TIME; \
  1269. state_heater_ ## NR = 0; \
  1270. WRITE_HEATER_ ## NR(0); \
  1271. } \
  1272. }
  1273. #define SLOW_PWM_ROUTINE(n) _SLOW_PWM_ROUTINE(n, soft_pwm[n])
  1274. #define PWM_OFF_ROUTINE(NR) \
  1275. if (soft_pwm_ ## NR < slow_pwm_count) { \
  1276. if (state_timer_heater_ ## NR == 0) { \
  1277. if (state_heater_ ## NR == 1) state_timer_heater_ ## NR = MIN_STATE_TIME; \
  1278. state_heater_ ## NR = 0; \
  1279. WRITE_HEATER_ ## NR (0); \
  1280. } \
  1281. }
  1282. if (slow_pwm_count == 0) {
  1283. SLOW_PWM_ROUTINE(0); // EXTRUDER 0
  1284. #if EXTRUDERS > 1
  1285. SLOW_PWM_ROUTINE(1); // EXTRUDER 1
  1286. #if EXTRUDERS > 2
  1287. SLOW_PWM_ROUTINE(2); // EXTRUDER 2
  1288. #if EXTRUDERS > 3
  1289. SLOW_PWM_ROUTINE(3); // EXTRUDER 3
  1290. #endif
  1291. #endif
  1292. #endif
  1293. #if HAS_HEATER_BED
  1294. _SLOW_PWM_ROUTINE(BED, soft_pwm_bed); // BED
  1295. #endif
  1296. } // slow_pwm_count == 0
  1297. PWM_OFF_ROUTINE(0); // EXTRUDER 0
  1298. #if EXTRUDERS > 1
  1299. PWM_OFF_ROUTINE(1); // EXTRUDER 1
  1300. #if EXTRUDERS > 2
  1301. PWM_OFF_ROUTINE(2); // EXTRUDER 2
  1302. #if EXTRUDERS > 3
  1303. PWM_OFF_ROUTINE(3); // EXTRUDER 3
  1304. #endif
  1305. #endif
  1306. #endif
  1307. #if HAS_HEATER_BED
  1308. PWM_OFF_ROUTINE(BED); // BED
  1309. #endif
  1310. #if ENABLED(FAN_SOFT_PWM)
  1311. if (pwm_count == 0) {
  1312. #if HAS_FAN0
  1313. soft_pwm_fan[0] = fanSpeedSoftPwm[0] / 2;
  1314. WRITE_FAN(soft_pwm_fan[0] > 0 ? 1 : 0);
  1315. #endif
  1316. #if HAS_FAN1
  1317. soft_pwm_fan[1] = fanSpeedSoftPwm[1] / 2;
  1318. WRITE_FAN1(soft_pwm_fan[1] > 0 ? 1 : 0);
  1319. #endif
  1320. #if HAS_FAN2
  1321. soft_pwm_fan[2] = fanSpeedSoftPwm[2] / 2;
  1322. WRITE_FAN2(soft_pwm_fan[2] > 0 ? 1 : 0);
  1323. #endif
  1324. }
  1325. #if HAS_FAN0
  1326. if (soft_pwm_fan[0] < pwm_count) WRITE_FAN(0);
  1327. #endif
  1328. #if HAS_FAN1
  1329. if (soft_pwm_fan[1] < pwm_count) WRITE_FAN1(0);
  1330. #endif
  1331. #if HAS_FAN2
  1332. if (soft_pwm_fan[2] < pwm_count) WRITE_FAN2(0);
  1333. #endif
  1334. #endif //FAN_SOFT_PWM
  1335. pwm_count += _BV(SOFT_PWM_SCALE);
  1336. pwm_count &= 0x7f;
  1337. // increment slow_pwm_count only every 64 pwm_count circa 65.5ms
  1338. if ((pwm_count % 64) == 0) {
  1339. slow_pwm_count++;
  1340. slow_pwm_count &= 0x7f;
  1341. // EXTRUDER 0
  1342. if (state_timer_heater_0 > 0) state_timer_heater_0--;
  1343. #if EXTRUDERS > 1 // EXTRUDER 1
  1344. if (state_timer_heater_1 > 0) state_timer_heater_1--;
  1345. #if EXTRUDERS > 2 // EXTRUDER 2
  1346. if (state_timer_heater_2 > 0) state_timer_heater_2--;
  1347. #if EXTRUDERS > 3 // EXTRUDER 3
  1348. if (state_timer_heater_3 > 0) state_timer_heater_3--;
  1349. #endif
  1350. #endif
  1351. #endif
  1352. #if HAS_HEATER_BED
  1353. if (state_timer_heater_BED > 0) state_timer_heater_BED--;
  1354. #endif
  1355. } // (pwm_count % 64) == 0
  1356. #endif // SLOW_PWM_HEATERS
  1357. #define SET_ADMUX_ADCSRA(pin) ADMUX = _BV(REFS0) | (pin & 0x07); SBI(ADCSRA, ADSC)
  1358. #ifdef MUX5
  1359. #define START_ADC(pin) if (pin > 7) ADCSRB = _BV(MUX5); else ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
  1360. #else
  1361. #define START_ADC(pin) ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
  1362. #endif
  1363. // Prepare or measure a sensor, each one every 12th frame
  1364. switch (temp_state) {
  1365. case PrepareTemp_0:
  1366. #if HAS_TEMP_0
  1367. START_ADC(TEMP_0_PIN);
  1368. #endif
  1369. lcd_buttons_update();
  1370. temp_state = MeasureTemp_0;
  1371. break;
  1372. case MeasureTemp_0:
  1373. #if HAS_TEMP_0
  1374. raw_temp_value[0] += ADC;
  1375. #endif
  1376. temp_state = PrepareTemp_BED;
  1377. break;
  1378. case PrepareTemp_BED:
  1379. #if HAS_TEMP_BED
  1380. START_ADC(TEMP_BED_PIN);
  1381. #endif
  1382. lcd_buttons_update();
  1383. temp_state = MeasureTemp_BED;
  1384. break;
  1385. case MeasureTemp_BED:
  1386. #if HAS_TEMP_BED
  1387. raw_temp_bed_value += ADC;
  1388. #endif
  1389. temp_state = PrepareTemp_1;
  1390. break;
  1391. case PrepareTemp_1:
  1392. #if HAS_TEMP_1
  1393. START_ADC(TEMP_1_PIN);
  1394. #endif
  1395. lcd_buttons_update();
  1396. temp_state = MeasureTemp_1;
  1397. break;
  1398. case MeasureTemp_1:
  1399. #if HAS_TEMP_1
  1400. raw_temp_value[1] += ADC;
  1401. #endif
  1402. temp_state = PrepareTemp_2;
  1403. break;
  1404. case PrepareTemp_2:
  1405. #if HAS_TEMP_2
  1406. START_ADC(TEMP_2_PIN);
  1407. #endif
  1408. lcd_buttons_update();
  1409. temp_state = MeasureTemp_2;
  1410. break;
  1411. case MeasureTemp_2:
  1412. #if HAS_TEMP_2
  1413. raw_temp_value[2] += ADC;
  1414. #endif
  1415. temp_state = PrepareTemp_3;
  1416. break;
  1417. case PrepareTemp_3:
  1418. #if HAS_TEMP_3
  1419. START_ADC(TEMP_3_PIN);
  1420. #endif
  1421. lcd_buttons_update();
  1422. temp_state = MeasureTemp_3;
  1423. break;
  1424. case MeasureTemp_3:
  1425. #if HAS_TEMP_3
  1426. raw_temp_value[3] += ADC;
  1427. #endif
  1428. temp_state = Prepare_FILWIDTH;
  1429. break;
  1430. case Prepare_FILWIDTH:
  1431. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1432. START_ADC(FILWIDTH_PIN);
  1433. #endif
  1434. lcd_buttons_update();
  1435. temp_state = Measure_FILWIDTH;
  1436. break;
  1437. case Measure_FILWIDTH:
  1438. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1439. // raw_filwidth_value += ADC; //remove to use an IIR filter approach
  1440. if (ADC > 102) { //check that ADC is reading a voltage > 0.5 volts, otherwise don't take in the data.
  1441. raw_filwidth_value -= (raw_filwidth_value >> 7); //multiply raw_filwidth_value by 127/128
  1442. raw_filwidth_value += ((unsigned long)ADC << 7); //add new ADC reading
  1443. }
  1444. #endif
  1445. temp_state = PrepareTemp_0;
  1446. temp_count++;
  1447. break;
  1448. case StartupDelay:
  1449. temp_state = PrepareTemp_0;
  1450. break;
  1451. // default:
  1452. // SERIAL_ERROR_START;
  1453. // SERIAL_ERRORLNPGM("Temp measurement error!");
  1454. // break;
  1455. } // switch(temp_state)
  1456. if (temp_count >= OVERSAMPLENR) { // 10 * 16 * 1/(16000000/64/256) = 164ms.
  1457. // Update the raw values if they've been read. Else we could be updating them during reading.
  1458. if (!temp_meas_ready) set_current_temp_raw();
  1459. // Filament Sensor - can be read any time since IIR filtering is used
  1460. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1461. current_raw_filwidth = raw_filwidth_value >> 10; // Divide to get to 0-16384 range since we used 1/128 IIR filter approach
  1462. #endif
  1463. temp_count = 0;
  1464. for (int i = 0; i < 4; i++) raw_temp_value[i] = 0;
  1465. raw_temp_bed_value = 0;
  1466. #if HAS_TEMP_0 && DISABLED(HEATER_0_USES_MAX6675)
  1467. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1468. #define GE0 <=
  1469. #else
  1470. #define GE0 >=
  1471. #endif
  1472. if (current_temperature_raw[0] GE0 maxttemp_raw[0]) max_temp_error(0);
  1473. if (minttemp_raw[0] GE0 current_temperature_raw[0]) min_temp_error(0);
  1474. #endif
  1475. #if HAS_TEMP_1 && EXTRUDERS > 1
  1476. #if HEATER_1_RAW_LO_TEMP > HEATER_1_RAW_HI_TEMP
  1477. #define GE1 <=
  1478. #else
  1479. #define GE1 >=
  1480. #endif
  1481. if (current_temperature_raw[1] GE1 maxttemp_raw[1]) max_temp_error(1);
  1482. if (minttemp_raw[1] GE1 current_temperature_raw[1]) min_temp_error(1);
  1483. #endif // TEMP_SENSOR_1
  1484. #if HAS_TEMP_2 && EXTRUDERS > 2
  1485. #if HEATER_2_RAW_LO_TEMP > HEATER_2_RAW_HI_TEMP
  1486. #define GE2 <=
  1487. #else
  1488. #define GE2 >=
  1489. #endif
  1490. if (current_temperature_raw[2] GE2 maxttemp_raw[2]) max_temp_error(2);
  1491. if (minttemp_raw[2] GE2 current_temperature_raw[2]) min_temp_error(2);
  1492. #endif // TEMP_SENSOR_2
  1493. #if HAS_TEMP_3 && EXTRUDERS > 3
  1494. #if HEATER_3_RAW_LO_TEMP > HEATER_3_RAW_HI_TEMP
  1495. #define GE3 <=
  1496. #else
  1497. #define GE3 >=
  1498. #endif
  1499. if (current_temperature_raw[3] GE3 maxttemp_raw[3]) max_temp_error(3);
  1500. if (minttemp_raw[3] GE3 current_temperature_raw[3]) min_temp_error(3);
  1501. #endif // TEMP_SENSOR_3
  1502. #if HAS_TEMP_BED
  1503. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1504. #define GEBED <=
  1505. #else
  1506. #define GEBED >=
  1507. #endif
  1508. if (current_temperature_bed_raw GEBED bed_maxttemp_raw) _temp_error(-1, PSTR(MSG_T_MAXTEMP), PSTR(MSG_ERR_MAXTEMP_BED));
  1509. if (bed_minttemp_raw GEBED current_temperature_bed_raw) _temp_error(-1, PSTR(MSG_T_MINTEMP), PSTR(MSG_ERR_MINTEMP_BED));
  1510. #endif
  1511. } // temp_count >= OVERSAMPLENR
  1512. #if ENABLED(BABYSTEPPING)
  1513. for (uint8_t axis = X_AXIS; axis <= Z_AXIS; axis++) {
  1514. int curTodo = babystepsTodo[axis]; //get rid of volatile for performance
  1515. if (curTodo > 0) {
  1516. babystep(axis,/*fwd*/true);
  1517. babystepsTodo[axis]--; //fewer to do next time
  1518. }
  1519. else if (curTodo < 0) {
  1520. babystep(axis,/*fwd*/false);
  1521. babystepsTodo[axis]++; //fewer to do next time
  1522. }
  1523. }
  1524. #endif //BABYSTEPPING
  1525. }
  1526. #if ENABLED(PIDTEMP)
  1527. // Apply the scale factors to the PID values
  1528. float scalePID_i(float i) { return i * PID_dT; }
  1529. float unscalePID_i(float i) { return i / PID_dT; }
  1530. float scalePID_d(float d) { return d / PID_dT; }
  1531. float unscalePID_d(float d) { return d * PID_dT; }
  1532. #endif //PIDTEMP