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 74KB

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