temperature.cpp 76 KB

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