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

temperature.cpp 93KB

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