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

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