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