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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 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 <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * temperature.cpp - temperature control
  24. */
  25. // Useful when debugging thermocouples
  26. //#define IGNORE_THERMOCOUPLE_ERRORS
  27. #include "../MarlinCore.h"
  28. #include "../HAL/shared/Delay.h"
  29. #include "../lcd/marlinui.h"
  30. #include "temperature.h"
  31. #include "endstops.h"
  32. #include "planner.h"
  33. #include "printcounter.h"
  34. #if EITHER(HAS_COOLER, LASER_COOLANT_FLOW_METER)
  35. #include "../feature/cooler.h"
  36. #include "../feature/spindle_laser.h"
  37. #endif
  38. #if ENABLED(USE_CONTROLLER_FAN)
  39. #include "../feature/controllerfan.h"
  40. #endif
  41. #if ENABLED(EMERGENCY_PARSER)
  42. #include "motion.h"
  43. #endif
  44. #if ENABLED(DWIN_CREALITY_LCD)
  45. #include "../lcd/e3v2/creality/dwin.h"
  46. #elif ENABLED(DWIN_LCD_PROUI)
  47. #include "../lcd/e3v2/proui/dwin.h"
  48. #endif
  49. #if ENABLED(EXTENSIBLE_UI)
  50. #include "../lcd/extui/ui_api.h"
  51. #endif
  52. #if ENABLED(HOST_PROMPT_SUPPORT)
  53. #include "../feature/host_actions.h"
  54. #endif
  55. #if HAS_TEMP_SENSOR
  56. #include "../gcode/gcode.h"
  57. #endif
  58. #if ENABLED(NOZZLE_PARK_FEATURE)
  59. #include "../libs/nozzle.h"
  60. #endif
  61. #if LASER_SAFETY_TIMEOUT_MS > 0
  62. #include "../feature/spindle_laser.h"
  63. #endif
  64. // MAX TC related macros
  65. #define TEMP_SENSOR_IS_MAX(n, M) (ENABLED(TEMP_SENSOR_##n##_IS_MAX##M) || (ENABLED(TEMP_SENSOR_REDUNDANT_IS_MAX##M) && REDUNDANT_TEMP_MATCH(SOURCE, E##n)))
  66. #define TEMP_SENSOR_IS_ANY_MAX_TC(n) (ENABLED(TEMP_SENSOR_##n##_IS_MAX_TC) || (ENABLED(TEMP_SENSOR_REDUNDANT_IS_MAX_TC) && REDUNDANT_TEMP_MATCH(SOURCE, E##n)))
  67. // LIB_MAX6675 can be added to the build_flags in platformio.ini to use a user-defined library
  68. // If LIB_MAX6675 is not on the build_flags then raw SPI reads will be used.
  69. #if HAS_MAX6675 && USE_LIB_MAX6675
  70. #include <max6675.h>
  71. #define HAS_MAX6675_LIBRARY 1
  72. #endif
  73. // LIB_MAX31855 can be added to the build_flags in platformio.ini to use a user-defined library.
  74. // If LIB_MAX31855 is not on the build_flags then raw SPI reads will be used.
  75. #if HAS_MAX31855 && USE_ADAFRUIT_MAX31855
  76. #include <Adafruit_MAX31855.h>
  77. #define HAS_MAX31855_LIBRARY 1
  78. typedef Adafruit_MAX31855 MAX31855;
  79. #endif
  80. #if HAS_MAX31865
  81. #if USE_ADAFRUIT_MAX31865
  82. #include <Adafruit_MAX31865.h>
  83. typedef Adafruit_MAX31865 MAX31865;
  84. #else
  85. #include "../libs/MAX31865.h"
  86. #endif
  87. #endif
  88. #if HAS_MAX6675_LIBRARY || HAS_MAX31855_LIBRARY || HAS_MAX31865
  89. #define HAS_MAXTC_LIBRARIES 1
  90. #endif
  91. // If we have a MAX TC with SCK and MISO pins defined, it's either on a separate/dedicated Hardware
  92. // SPI bus, or some pins for Software SPI. Alternate Hardware SPI buses are not supported yet, so
  93. // your SPI options are:
  94. //
  95. // 1. Only CS pin(s) defined: Hardware SPI on the default bus (usually the SD card SPI).
  96. // 2. CS, MISO, and SCK pins defined: Software SPI on a separate bus, as defined by MISO, SCK.
  97. // 3. CS, MISO, and SCK pins w/ FORCE_HW_SPI: Hardware SPI on the default bus, ignoring MISO, SCK.
  98. //
  99. #if TEMP_SENSOR_IS_ANY_MAX_TC(0) && TEMP_SENSOR_0_HAS_SPI_PINS && DISABLED(TEMP_SENSOR_FORCE_HW_SPI)
  100. #define TEMP_SENSOR_0_USES_SW_SPI 1
  101. #endif
  102. #if TEMP_SENSOR_IS_ANY_MAX_TC(1) && TEMP_SENSOR_1_HAS_SPI_PINS && DISABLED(TEMP_SENSOR_FORCE_HW_SPI)
  103. #define TEMP_SENSOR_1_USES_SW_SPI 1
  104. #endif
  105. #if (TEMP_SENSOR_0_USES_SW_SPI || TEMP_SENSOR_1_USES_SW_SPI) && !HAS_MAXTC_LIBRARIES
  106. #include "../libs/private_spi.h"
  107. #define HAS_MAXTC_SW_SPI 1
  108. // Define pins for SPI-based sensors
  109. #if TEMP_SENSOR_0_USES_SW_SPI
  110. #define SW_SPI_SCK_PIN TEMP_0_SCK_PIN
  111. #define SW_SPI_MISO_PIN TEMP_0_MISO_PIN
  112. #if PIN_EXISTS(TEMP_0_MOSI)
  113. #define SW_SPI_MOSI_PIN TEMP_0_MOSI_PIN
  114. #endif
  115. #else
  116. #define SW_SPI_SCK_PIN TEMP_1_SCK_PIN
  117. #define SW_SPI_MISO_PIN TEMP_1_MISO_PIN
  118. #if PIN_EXISTS(TEMP_1_MOSI)
  119. #define SW_SPI_MOSI_PIN TEMP_1_MOSI_PIN
  120. #endif
  121. #endif
  122. #ifndef SW_SPI_MOSI_PIN
  123. #define SW_SPI_MOSI_PIN SD_MOSI_PIN
  124. #endif
  125. #endif
  126. #if ENABLED(MPCTEMP)
  127. #include <math.h>
  128. #include "probe.h"
  129. #endif
  130. #if EITHER(MPCTEMP, PID_EXTRUSION_SCALING)
  131. #include "stepper.h"
  132. #endif
  133. #if ENABLED(BABYSTEPPING) && DISABLED(INTEGRATED_BABYSTEPPING)
  134. #include "../feature/babystep.h"
  135. #endif
  136. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  137. #include "../feature/filwidth.h"
  138. #endif
  139. #if HAS_POWER_MONITOR
  140. #include "../feature/power_monitor.h"
  141. #endif
  142. #if ENABLED(EMERGENCY_PARSER)
  143. #include "../feature/e_parser.h"
  144. #endif
  145. #if ENABLED(PRINTER_EVENT_LEDS)
  146. #include "../feature/leds/printer_event_leds.h"
  147. #endif
  148. #if ENABLED(JOYSTICK)
  149. #include "../feature/joystick.h"
  150. #endif
  151. #if ENABLED(SINGLENOZZLE)
  152. #include "tool_change.h"
  153. #endif
  154. #if HAS_BEEPER
  155. #include "../libs/buzzer.h"
  156. #endif
  157. #if HAS_SERVOS
  158. #include "servo.h"
  159. #endif
  160. #if ANY(TEMP_SENSOR_0_IS_THERMISTOR, TEMP_SENSOR_1_IS_THERMISTOR, TEMP_SENSOR_2_IS_THERMISTOR, TEMP_SENSOR_3_IS_THERMISTOR, \
  161. TEMP_SENSOR_4_IS_THERMISTOR, TEMP_SENSOR_5_IS_THERMISTOR, TEMP_SENSOR_6_IS_THERMISTOR, TEMP_SENSOR_7_IS_THERMISTOR )
  162. #define HAS_HOTEND_THERMISTOR 1
  163. #endif
  164. #if HAS_HOTEND_THERMISTOR
  165. #define NEXT_TEMPTABLE(N) ,TEMPTABLE_##N
  166. #define NEXT_TEMPTABLE_LEN(N) ,TEMPTABLE_##N##_LEN
  167. static const temp_entry_t* heater_ttbl_map[HOTENDS] = ARRAY_BY_HOTENDS(TEMPTABLE_0 REPEAT_S(1, HOTENDS, NEXT_TEMPTABLE));
  168. static constexpr uint8_t heater_ttbllen_map[HOTENDS] = ARRAY_BY_HOTENDS(TEMPTABLE_0_LEN REPEAT_S(1, HOTENDS, NEXT_TEMPTABLE_LEN));
  169. #endif
  170. Temperature thermalManager;
  171. PGMSTR(str_t_thermal_runaway, STR_T_THERMAL_RUNAWAY);
  172. PGMSTR(str_t_temp_malfunction, STR_T_MALFUNCTION);
  173. PGMSTR(str_t_heating_failed, STR_T_HEATING_FAILED);
  174. /**
  175. * Macros to include the heater id in temp errors. The compiler's dead-code
  176. * elimination should (hopefully) optimize out the unused strings.
  177. */
  178. #if HAS_HEATED_BED
  179. #define _BED_FSTR(h) (h) == H_BED ? GET_TEXT_F(MSG_BED) :
  180. #else
  181. #define _BED_FSTR(h)
  182. #endif
  183. #if HAS_HEATED_CHAMBER
  184. #define _CHAMBER_FSTR(h) (h) == H_CHAMBER ? GET_TEXT_F(MSG_CHAMBER) :
  185. #else
  186. #define _CHAMBER_FSTR(h)
  187. #endif
  188. #if HAS_COOLER
  189. #define _COOLER_FSTR(h) (h) == H_COOLER ? GET_TEXT_F(MSG_COOLER) :
  190. #else
  191. #define _COOLER_FSTR(h)
  192. #endif
  193. #define _E_FSTR(h,N) ((HOTENDS) > N && (h) == N) ? F(STR_E##N) :
  194. #define HEATER_FSTR(h) _BED_FSTR(h) _CHAMBER_FSTR(h) _COOLER_FSTR(h) _E_FSTR(h,1) _E_FSTR(h,2) _E_FSTR(h,3) _E_FSTR(h,4) _E_FSTR(h,5) _E_FSTR(h,6) _E_FSTR(h,7) F(STR_E0)
  195. //
  196. // Initialize MAX TC objects/SPI
  197. //
  198. #if HAS_MAX_TC
  199. #if HAS_MAXTC_SW_SPI
  200. // Initialize SoftSPI for non-lib Software SPI; Libraries take care of it themselves.
  201. template<uint8_t MisoPin, uint8_t MosiPin, uint8_t SckPin>
  202. SoftSPI<MisoPin, MosiPin, SckPin> SPIclass<MisoPin, MosiPin, SckPin>::softSPI;
  203. SPIclass<SW_SPI_MISO_PIN, SW_SPI_MOSI_PIN, SW_SPI_SCK_PIN> max_tc_spi;
  204. #endif
  205. #define MAXTC_INIT(n, M) \
  206. MAX##M max##M##_##n = MAX##M( \
  207. TEMP_##n##_CS_PIN \
  208. OPTARG(_MAX31865_##n##_SW, TEMP_##n##_MOSI_PIN) \
  209. OPTARG(TEMP_SENSOR_##n##_USES_SW_SPI, TEMP_##n##_MISO_PIN, TEMP_##n##_SCK_PIN) \
  210. OPTARG(LARGE_PINMAP, HIGH) \
  211. )
  212. #if HAS_MAX6675_LIBRARY
  213. #if TEMP_SENSOR_IS_MAX(0, 6675)
  214. MAXTC_INIT(0, 6675);
  215. #endif
  216. #if TEMP_SENSOR_IS_MAX(1, 6675)
  217. MAXTC_INIT(1, 6675);
  218. #endif
  219. #endif
  220. #if HAS_MAX31855_LIBRARY
  221. #if TEMP_SENSOR_IS_MAX(0, 31855)
  222. MAXTC_INIT(0, 31855);
  223. #endif
  224. #if TEMP_SENSOR_IS_MAX(1, 31855)
  225. MAXTC_INIT(1, 31855);
  226. #endif
  227. #endif
  228. // MAX31865 always uses a library, unlike '55 & 6675
  229. #if HAS_MAX31865
  230. #define _MAX31865_0_SW TEMP_SENSOR_0_USES_SW_SPI
  231. #define _MAX31865_1_SW TEMP_SENSOR_1_USES_SW_SPI
  232. #if TEMP_SENSOR_IS_MAX(0, 31865)
  233. MAXTC_INIT(0, 31865);
  234. #endif
  235. #if TEMP_SENSOR_IS_MAX(1, 31865)
  236. MAXTC_INIT(1, 31865);
  237. #endif
  238. #undef _MAX31865_0_SW
  239. #undef _MAX31865_1_SW
  240. #endif
  241. #undef MAXTC_INIT
  242. #endif
  243. /**
  244. * public:
  245. */
  246. #if ENABLED(NO_FAN_SLOWING_IN_PID_TUNING)
  247. bool Temperature::adaptive_fan_slowing = true;
  248. #endif
  249. #if HAS_HOTEND
  250. hotend_info_t Temperature::temp_hotend[HOTENDS];
  251. #define _HMT(N) HEATER_##N##_MAXTEMP,
  252. const celsius_t Temperature::hotend_maxtemp[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_MAXTEMP, HEATER_1_MAXTEMP, HEATER_2_MAXTEMP, HEATER_3_MAXTEMP, HEATER_4_MAXTEMP, HEATER_5_MAXTEMP, HEATER_6_MAXTEMP, HEATER_7_MAXTEMP);
  253. #endif
  254. #if HAS_TEMP_REDUNDANT
  255. redundant_info_t Temperature::temp_redundant;
  256. #endif
  257. #if EITHER(AUTO_POWER_E_FANS, HAS_FANCHECK)
  258. uint8_t Temperature::autofan_speed[HOTENDS]; // = { 0 }
  259. #endif
  260. #if ENABLED(AUTO_POWER_CHAMBER_FAN)
  261. uint8_t Temperature::chamberfan_speed; // = 0
  262. #endif
  263. #if ENABLED(AUTO_POWER_COOLER_FAN)
  264. uint8_t Temperature::coolerfan_speed; // = 0
  265. #endif
  266. #if BOTH(FAN_SOFT_PWM, USE_CONTROLLER_FAN)
  267. uint8_t Temperature::soft_pwm_controller_speed;
  268. #endif
  269. // Init fans according to whether they're native PWM or Software PWM
  270. #ifdef BOARD_OPENDRAIN_MOSFETS
  271. #define _INIT_SOFT_FAN(P) OUT_WRITE_OD(P, FAN_INVERTING ? LOW : HIGH)
  272. #else
  273. #define _INIT_SOFT_FAN(P) OUT_WRITE(P, FAN_INVERTING ? LOW : HIGH)
  274. #endif
  275. #if ENABLED(FAN_SOFT_PWM)
  276. #define _INIT_FAN_PIN(P) _INIT_SOFT_FAN(P)
  277. #else
  278. #define _INIT_FAN_PIN(P) do{ if (PWM_PIN(P)) SET_PWM(P); else _INIT_SOFT_FAN(P); }while(0)
  279. #endif
  280. #if ENABLED(FAST_PWM_FAN)
  281. #define SET_FAST_PWM_FREQ(P) hal.set_pwm_frequency(pin_t(P), FAST_PWM_FAN_FREQUENCY)
  282. #else
  283. #define SET_FAST_PWM_FREQ(P) NOOP
  284. #endif
  285. #define INIT_FAN_PIN(P) do{ _INIT_FAN_PIN(P); SET_FAST_PWM_FREQ(P); }while(0)
  286. // HAS_FAN does not include CONTROLLER_FAN
  287. #if HAS_FAN
  288. uint8_t Temperature::fan_speed[FAN_COUNT]; // = { 0 }
  289. #if ENABLED(EXTRA_FAN_SPEED)
  290. Temperature::extra_fan_t Temperature::extra_fan_speed[FAN_COUNT];
  291. /**
  292. * Handle the M106 P<fan> T<speed> command:
  293. * T1 = Restore fan speed saved on the last T2
  294. * T2 = Save the fan speed, then set to the last T<3-255> value
  295. * T<3-255> = Set the "extra fan speed"
  296. */
  297. void Temperature::set_temp_fan_speed(const uint8_t fan, const uint16_t command_or_speed) {
  298. switch (command_or_speed) {
  299. case 1:
  300. set_fan_speed(fan, extra_fan_speed[fan].saved);
  301. break;
  302. case 2:
  303. extra_fan_speed[fan].saved = fan_speed[fan];
  304. set_fan_speed(fan, extra_fan_speed[fan].speed);
  305. break;
  306. default:
  307. extra_fan_speed[fan].speed = _MIN(command_or_speed, 255U);
  308. break;
  309. }
  310. }
  311. #endif
  312. #if EITHER(PROBING_FANS_OFF, ADVANCED_PAUSE_FANS_PAUSE)
  313. bool Temperature::fans_paused; // = false;
  314. uint8_t Temperature::saved_fan_speed[FAN_COUNT]; // = { 0 }
  315. #endif
  316. #if ENABLED(ADAPTIVE_FAN_SLOWING)
  317. uint8_t Temperature::fan_speed_scaler[FAN_COUNT] = ARRAY_N_1(FAN_COUNT, 128);
  318. #endif
  319. /**
  320. * Set the print fan speed for a target extruder
  321. */
  322. void Temperature::set_fan_speed(uint8_t fan, uint16_t speed) {
  323. NOMORE(speed, 255U);
  324. #if ENABLED(SINGLENOZZLE_STANDBY_FAN)
  325. if (fan != active_extruder) {
  326. if (fan < EXTRUDERS) singlenozzle_fan_speed[fan] = speed;
  327. return;
  328. }
  329. #endif
  330. TERN_(SINGLENOZZLE, if (fan < EXTRUDERS) fan = 0); // Always fan 0 for SINGLENOZZLE E fan
  331. if (fan >= FAN_COUNT) return;
  332. fan_speed[fan] = speed;
  333. #if REDUNDANT_PART_COOLING_FAN
  334. if (fan == 0) fan_speed[REDUNDANT_PART_COOLING_FAN] = speed;
  335. #endif
  336. TERN_(REPORT_FAN_CHANGE, report_fan_speed(fan));
  337. }
  338. #if ENABLED(REPORT_FAN_CHANGE)
  339. /**
  340. * Report print fan speed for a target extruder
  341. */
  342. void Temperature::report_fan_speed(const uint8_t fan) {
  343. if (fan >= FAN_COUNT) return;
  344. PORT_REDIRECT(SerialMask::All);
  345. SERIAL_ECHOLNPGM("M106 P", fan, " S", fan_speed[fan]);
  346. }
  347. #endif
  348. #if EITHER(PROBING_FANS_OFF, ADVANCED_PAUSE_FANS_PAUSE)
  349. void Temperature::set_fans_paused(const bool p) {
  350. if (p != fans_paused) {
  351. fans_paused = p;
  352. if (p)
  353. FANS_LOOP(i) { saved_fan_speed[i] = fan_speed[i]; fan_speed[i] = 0; }
  354. else
  355. FANS_LOOP(i) fan_speed[i] = saved_fan_speed[i];
  356. }
  357. }
  358. #endif
  359. #endif // HAS_FAN
  360. #if WATCH_HOTENDS
  361. hotend_watch_t Temperature::watch_hotend[HOTENDS]; // = { { 0 } }
  362. #endif
  363. #if HEATER_IDLE_HANDLER
  364. Temperature::heater_idle_t Temperature::heater_idle[NR_HEATER_IDLE]; // = { { 0 } }
  365. #endif
  366. #if HAS_HEATED_BED
  367. bed_info_t Temperature::temp_bed; // = { 0 }
  368. // Init min and max temp with extreme values to prevent false errors during startup
  369. raw_adc_t Temperature::mintemp_raw_BED = TEMP_SENSOR_BED_RAW_LO_TEMP,
  370. Temperature::maxtemp_raw_BED = TEMP_SENSOR_BED_RAW_HI_TEMP;
  371. TERN_(WATCH_BED, bed_watch_t Temperature::watch_bed); // = { 0 }
  372. IF_DISABLED(PIDTEMPBED, millis_t Temperature::next_bed_check_ms);
  373. #endif
  374. #if HAS_TEMP_CHAMBER
  375. chamber_info_t Temperature::temp_chamber; // = { 0 }
  376. #if HAS_HEATED_CHAMBER
  377. millis_t next_cool_check_ms_2 = 0;
  378. celsius_float_t old_temp = 9999;
  379. raw_adc_t Temperature::mintemp_raw_CHAMBER = TEMP_SENSOR_CHAMBER_RAW_LO_TEMP,
  380. Temperature::maxtemp_raw_CHAMBER = TEMP_SENSOR_CHAMBER_RAW_HI_TEMP;
  381. TERN_(WATCH_CHAMBER, chamber_watch_t Temperature::watch_chamber{0});
  382. IF_DISABLED(PIDTEMPCHAMBER, millis_t Temperature::next_chamber_check_ms);
  383. #endif
  384. #endif
  385. #if HAS_TEMP_COOLER
  386. cooler_info_t Temperature::temp_cooler; // = { 0 }
  387. #if HAS_COOLER
  388. bool flag_cooler_state;
  389. //bool flag_cooler_excess = false;
  390. celsius_float_t previous_temp = 9999;
  391. raw_adc_t Temperature::mintemp_raw_COOLER = TEMP_SENSOR_COOLER_RAW_LO_TEMP,
  392. Temperature::maxtemp_raw_COOLER = TEMP_SENSOR_COOLER_RAW_HI_TEMP;
  393. #if WATCH_COOLER
  394. cooler_watch_t Temperature::watch_cooler{0};
  395. #endif
  396. millis_t Temperature::next_cooler_check_ms, Temperature::cooler_fan_flush_ms;
  397. #endif
  398. #endif
  399. #if HAS_TEMP_PROBE
  400. probe_info_t Temperature::temp_probe; // = { 0 }
  401. #endif
  402. #if HAS_TEMP_BOARD
  403. board_info_t Temperature::temp_board; // = { 0 }
  404. #if ENABLED(THERMAL_PROTECTION_BOARD)
  405. raw_adc_t Temperature::mintemp_raw_BOARD = TEMP_SENSOR_BOARD_RAW_LO_TEMP,
  406. Temperature::maxtemp_raw_BOARD = TEMP_SENSOR_BOARD_RAW_HI_TEMP;
  407. #endif
  408. #endif
  409. #if BOTH(HAS_MARLINUI_MENU, PREVENT_COLD_EXTRUSION) && E_MANUAL > 0
  410. bool Temperature::allow_cold_extrude_override = false;
  411. #else
  412. constexpr bool Temperature::allow_cold_extrude_override;
  413. #endif
  414. #if ENABLED(PREVENT_COLD_EXTRUSION)
  415. bool Temperature::allow_cold_extrude = false;
  416. celsius_t Temperature::extrude_min_temp = EXTRUDE_MINTEMP;
  417. #endif
  418. #if HAS_ADC_BUTTONS
  419. uint32_t Temperature::current_ADCKey_raw = HAL_ADC_RANGE;
  420. uint16_t Temperature::ADCKey_count = 0;
  421. #endif
  422. #if ENABLED(PID_EXTRUSION_SCALING)
  423. int16_t Temperature::lpq_len; // Initialized in settings.cpp
  424. #endif
  425. /**
  426. * private:
  427. */
  428. volatile bool Temperature::raw_temps_ready = false;
  429. #if ENABLED(PID_EXTRUSION_SCALING)
  430. int32_t Temperature::pes_e_position, Temperature::lpq[LPQ_MAX_LEN];
  431. lpq_ptr_t Temperature::lpq_ptr = 0;
  432. #endif
  433. #if ENABLED(MPCTEMP)
  434. int32_t Temperature::mpc_e_position; // = 0
  435. #endif
  436. #define TEMPDIR(N) ((TEMP_SENSOR_##N##_RAW_LO_TEMP) < (TEMP_SENSOR_##N##_RAW_HI_TEMP) ? 1 : -1)
  437. #define TP_CMP(S,A,B) (TEMPDIR(S) < 0 ? ((A)<(B)) : ((A)>(B)))
  438. #if HAS_HOTEND
  439. // Init mintemp and maxtemp with extreme values to prevent false errors during startup
  440. constexpr temp_range_t sensor_heater_0 { TEMP_SENSOR_0_RAW_LO_TEMP, TEMP_SENSOR_0_RAW_HI_TEMP, 0, 16383 },
  441. sensor_heater_1 { TEMP_SENSOR_1_RAW_LO_TEMP, TEMP_SENSOR_1_RAW_HI_TEMP, 0, 16383 },
  442. sensor_heater_2 { TEMP_SENSOR_2_RAW_LO_TEMP, TEMP_SENSOR_2_RAW_HI_TEMP, 0, 16383 },
  443. sensor_heater_3 { TEMP_SENSOR_3_RAW_LO_TEMP, TEMP_SENSOR_3_RAW_HI_TEMP, 0, 16383 },
  444. sensor_heater_4 { TEMP_SENSOR_4_RAW_LO_TEMP, TEMP_SENSOR_4_RAW_HI_TEMP, 0, 16383 },
  445. sensor_heater_5 { TEMP_SENSOR_5_RAW_LO_TEMP, TEMP_SENSOR_5_RAW_HI_TEMP, 0, 16383 },
  446. sensor_heater_6 { TEMP_SENSOR_6_RAW_LO_TEMP, TEMP_SENSOR_6_RAW_HI_TEMP, 0, 16383 },
  447. sensor_heater_7 { TEMP_SENSOR_7_RAW_LO_TEMP, TEMP_SENSOR_7_RAW_HI_TEMP, 0, 16383 };
  448. 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, sensor_heater_6, sensor_heater_7);
  449. #endif
  450. #if MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED > 1
  451. uint8_t Temperature::consecutive_low_temperature_error[HOTENDS] = { 0 };
  452. #endif
  453. #if MILLISECONDS_PREHEAT_TIME > 0
  454. millis_t Temperature::preheat_end_time[HOTENDS] = { 0 };
  455. #endif
  456. #if HAS_FAN_LOGIC
  457. constexpr millis_t Temperature::fan_update_interval_ms;
  458. millis_t Temperature::fan_update_ms = 0;
  459. #endif
  460. #if ENABLED(FAN_SOFT_PWM)
  461. uint8_t Temperature::soft_pwm_amount_fan[FAN_COUNT],
  462. Temperature::soft_pwm_count_fan[FAN_COUNT];
  463. #endif
  464. #if ENABLED(SINGLENOZZLE_STANDBY_TEMP)
  465. celsius_t Temperature::singlenozzle_temp[EXTRUDERS];
  466. #endif
  467. #if ENABLED(SINGLENOZZLE_STANDBY_FAN)
  468. uint8_t Temperature::singlenozzle_fan_speed[EXTRUDERS];
  469. #endif
  470. #if ENABLED(PROBING_HEATERS_OFF)
  471. bool Temperature::paused_for_probing;
  472. #endif
  473. /**
  474. * public:
  475. * Class and Instance Methods
  476. */
  477. #if HAS_PID_HEATING
  478. inline void say_default_() { SERIAL_ECHOPGM("#define DEFAULT_"); }
  479. /**
  480. * PID Autotuning (M303)
  481. *
  482. * Alternately heat and cool the nozzle, observing its behavior to
  483. * determine the best PID values to achieve a stable temperature.
  484. * Needs sufficient heater power to make some overshoot at target
  485. * temperature to succeed.
  486. */
  487. void Temperature::PID_autotune(const celsius_t target, const heater_id_t heater_id, const int8_t ncycles, const bool set_result/*=false*/) {
  488. celsius_float_t current_temp = 0.0;
  489. int cycles = 0;
  490. bool heating = true;
  491. millis_t next_temp_ms = millis(), t1 = next_temp_ms, t2 = next_temp_ms;
  492. long t_high = 0, t_low = 0;
  493. PID_t tune_pid = { 0, 0, 0 };
  494. celsius_float_t maxT = 0, minT = 10000;
  495. const bool isbed = (heater_id == H_BED),
  496. ischamber = (heater_id == H_CHAMBER);
  497. #if ENABLED(PIDTEMPCHAMBER)
  498. #define C_TERN(T,A,B) ((T) ? (A) : (B))
  499. #else
  500. #define C_TERN(T,A,B) (B)
  501. #endif
  502. #if ENABLED(PIDTEMPBED)
  503. #define B_TERN(T,A,B) ((T) ? (A) : (B))
  504. #else
  505. #define B_TERN(T,A,B) (B)
  506. #endif
  507. #define GHV(C,B,H) C_TERN(ischamber, C, B_TERN(isbed, B, H))
  508. #define SHV(V) C_TERN(ischamber, temp_chamber.soft_pwm_amount = V, B_TERN(isbed, temp_bed.soft_pwm_amount = V, temp_hotend[heater_id].soft_pwm_amount = V))
  509. #define ONHEATINGSTART() C_TERN(ischamber, printerEventLEDs.onChamberHeatingStart(), B_TERN(isbed, printerEventLEDs.onBedHeatingStart(), printerEventLEDs.onHotendHeatingStart()))
  510. #define ONHEATING(S,C,T) C_TERN(ischamber, printerEventLEDs.onChamberHeating(S,C,T), B_TERN(isbed, printerEventLEDs.onBedHeating(S,C,T), printerEventLEDs.onHotendHeating(S,C,T)))
  511. #define WATCH_PID DISABLED(NO_WATCH_PID_TUNING) && (BOTH(WATCH_CHAMBER, PIDTEMPCHAMBER) || BOTH(WATCH_BED, PIDTEMPBED) || BOTH(WATCH_HOTENDS, PIDTEMP))
  512. #if WATCH_PID
  513. #if BOTH(THERMAL_PROTECTION_CHAMBER, PIDTEMPCHAMBER)
  514. #define C_GTV(T,A,B) ((T) ? (A) : (B))
  515. #else
  516. #define C_GTV(T,A,B) (B)
  517. #endif
  518. #if BOTH(THERMAL_PROTECTION_BED, PIDTEMPBED)
  519. #define B_GTV(T,A,B) ((T) ? (A) : (B))
  520. #else
  521. #define B_GTV(T,A,B) (B)
  522. #endif
  523. #define GTV(C,B,H) C_GTV(ischamber, C, B_GTV(isbed, B, H))
  524. const uint16_t watch_temp_period = GTV(WATCH_CHAMBER_TEMP_PERIOD, WATCH_BED_TEMP_PERIOD, WATCH_TEMP_PERIOD);
  525. const uint8_t watch_temp_increase = GTV(WATCH_CHAMBER_TEMP_INCREASE, WATCH_BED_TEMP_INCREASE, WATCH_TEMP_INCREASE);
  526. const celsius_float_t watch_temp_target = celsius_float_t(target - (watch_temp_increase + GTV(TEMP_CHAMBER_HYSTERESIS, TEMP_BED_HYSTERESIS, TEMP_HYSTERESIS) + 1));
  527. millis_t temp_change_ms = next_temp_ms + SEC_TO_MS(watch_temp_period);
  528. celsius_float_t next_watch_temp = 0.0;
  529. bool heated = false;
  530. #endif
  531. TERN_(HAS_FAN_LOGIC, fan_update_ms = next_temp_ms + fan_update_interval_ms);
  532. TERN_(EXTENSIBLE_UI, ExtUI::onPidTuning(ExtUI::result_t::PID_STARTED));
  533. TERN_(DWIN_LCD_PROUI, DWIN_PidTuning(isbed ? PID_BED_START : PID_EXTR_START));
  534. if (target > GHV(CHAMBER_MAX_TARGET, BED_MAX_TARGET, temp_range[heater_id].maxtemp - (HOTEND_OVERSHOOT))) {
  535. SERIAL_ECHOPGM(STR_PID_AUTOTUNE);
  536. SERIAL_ECHOLNPGM(STR_PID_TEMP_TOO_HIGH);
  537. TERN_(EXTENSIBLE_UI, ExtUI::onPidTuning(ExtUI::result_t::PID_TEMP_TOO_HIGH));
  538. TERN_(DWIN_LCD_PROUI, DWIN_PidTuning(PID_TEMP_TOO_HIGH));
  539. TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_TEMP_TOO_HIGH)));
  540. return;
  541. }
  542. SERIAL_ECHOPGM(STR_PID_AUTOTUNE);
  543. SERIAL_ECHOLNPGM(STR_PID_AUTOTUNE_START);
  544. disable_all_heaters();
  545. TERN_(AUTO_POWER_CONTROL, powerManager.power_on());
  546. long bias = GHV(MAX_CHAMBER_POWER, MAX_BED_POWER, PID_MAX) >> 1, d = bias;
  547. SHV(bias);
  548. #if ENABLED(PRINTER_EVENT_LEDS)
  549. const celsius_float_t start_temp = GHV(degChamber(), degBed(), degHotend(heater_id));
  550. LEDColor color = ONHEATINGSTART();
  551. #endif
  552. TERN_(NO_FAN_SLOWING_IN_PID_TUNING, adaptive_fan_slowing = false);
  553. LCD_MESSAGE(MSG_HEATING);
  554. // PID Tuning loop
  555. wait_for_heatup = true;
  556. while (wait_for_heatup) { // Can be interrupted with M108
  557. const millis_t ms = millis();
  558. if (updateTemperaturesIfReady()) { // temp sample ready
  559. // Get the current temperature and constrain it
  560. current_temp = GHV(degChamber(), degBed(), degHotend(heater_id));
  561. NOLESS(maxT, current_temp);
  562. NOMORE(minT, current_temp);
  563. #if ENABLED(PRINTER_EVENT_LEDS)
  564. ONHEATING(start_temp, current_temp, target);
  565. #endif
  566. TERN_(HAS_FAN_LOGIC, manage_extruder_fans(ms));
  567. if (heating && current_temp > target && ELAPSED(ms, t2 + 5000UL)) {
  568. heating = false;
  569. SHV((bias - d) >> 1);
  570. t1 = ms;
  571. t_high = t1 - t2;
  572. maxT = target;
  573. }
  574. if (!heating && current_temp < target && ELAPSED(ms, t1 + 5000UL)) {
  575. heating = true;
  576. t2 = ms;
  577. t_low = t2 - t1;
  578. if (cycles > 0) {
  579. const long max_pow = GHV(MAX_CHAMBER_POWER, MAX_BED_POWER, PID_MAX);
  580. bias += (d * (t_high - t_low)) / (t_low + t_high);
  581. LIMIT(bias, 20, max_pow - 20);
  582. d = (bias > max_pow >> 1) ? max_pow - 1 - bias : bias;
  583. SERIAL_ECHOPGM(STR_BIAS, bias, STR_D_COLON, d, STR_T_MIN, minT, STR_T_MAX, maxT);
  584. if (cycles > 2) {
  585. const float Ku = (4.0f * d) / (float(M_PI) * (maxT - minT) * 0.5f),
  586. Tu = float(t_low + t_high) * 0.001f,
  587. pf = (ischamber || isbed) ? 0.2f : 0.6f,
  588. df = (ischamber || isbed) ? 1.0f / 3.0f : 1.0f / 8.0f;
  589. tune_pid.Kp = Ku * pf;
  590. tune_pid.Ki = tune_pid.Kp * 2.0f / Tu;
  591. tune_pid.Kd = tune_pid.Kp * Tu * df;
  592. SERIAL_ECHOLNPGM(STR_KU, Ku, STR_TU, Tu);
  593. if (ischamber || isbed)
  594. SERIAL_ECHOLNPGM(" No overshoot");
  595. else
  596. SERIAL_ECHOLNPGM(STR_CLASSIC_PID);
  597. SERIAL_ECHOLNPGM(STR_KP, tune_pid.Kp, STR_KI, tune_pid.Ki, STR_KD, tune_pid.Kd);
  598. }
  599. }
  600. SHV((bias + d) >> 1);
  601. TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT(MSG_PID_CYCLE), cycles, ncycles));
  602. cycles++;
  603. minT = target;
  604. }
  605. }
  606. // Did the temperature overshoot very far?
  607. #ifndef MAX_OVERSHOOT_PID_AUTOTUNE
  608. #define MAX_OVERSHOOT_PID_AUTOTUNE 30
  609. #endif
  610. if (current_temp > target + MAX_OVERSHOOT_PID_AUTOTUNE) {
  611. SERIAL_ECHOPGM(STR_PID_AUTOTUNE);
  612. SERIAL_ECHOLNPGM(STR_PID_TEMP_TOO_HIGH);
  613. TERN_(EXTENSIBLE_UI, ExtUI::onPidTuning(ExtUI::result_t::PID_TEMP_TOO_HIGH));
  614. TERN_(DWIN_LCD_PROUI, DWIN_PidTuning(PID_TEMP_TOO_HIGH));
  615. TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_TEMP_TOO_HIGH)));
  616. break;
  617. }
  618. // Report heater states every 2 seconds
  619. if (ELAPSED(ms, next_temp_ms)) {
  620. #if HAS_TEMP_SENSOR
  621. print_heater_states(heater_id < 0 ? active_extruder : (int8_t)heater_id);
  622. SERIAL_EOL();
  623. #endif
  624. next_temp_ms = ms + 2000UL;
  625. // Make sure heating is actually working
  626. #if WATCH_PID
  627. if (BOTH(WATCH_BED, WATCH_HOTENDS) || isbed == DISABLED(WATCH_HOTENDS) || ischamber == DISABLED(WATCH_HOTENDS)) {
  628. if (!heated) { // If not yet reached target...
  629. if (current_temp > next_watch_temp) { // Over the watch temp?
  630. next_watch_temp = current_temp + watch_temp_increase; // - set the next temp to watch for
  631. temp_change_ms = ms + SEC_TO_MS(watch_temp_period); // - move the expiration timer up
  632. if (current_temp > watch_temp_target) heated = true; // - Flag if target temperature reached
  633. }
  634. else if (ELAPSED(ms, temp_change_ms)) // Watch timer expired
  635. _temp_error(heater_id, FPSTR(str_t_heating_failed), GET_TEXT_F(MSG_HEATING_FAILED_LCD));
  636. }
  637. else if (current_temp < target - (MAX_OVERSHOOT_PID_AUTOTUNE)) // Heated, then temperature fell too far?
  638. _temp_error(heater_id, FPSTR(str_t_thermal_runaway), GET_TEXT_F(MSG_THERMAL_RUNAWAY));
  639. }
  640. #endif
  641. } // every 2 seconds
  642. // Timeout after MAX_CYCLE_TIME_PID_AUTOTUNE minutes since the last undershoot/overshoot cycle
  643. #ifndef MAX_CYCLE_TIME_PID_AUTOTUNE
  644. #define MAX_CYCLE_TIME_PID_AUTOTUNE 20L
  645. #endif
  646. if ((ms - _MIN(t1, t2)) > (MAX_CYCLE_TIME_PID_AUTOTUNE * 60L * 1000L)) {
  647. TERN_(DWIN_CREALITY_LCD, DWIN_Popup_Temperature(0));
  648. TERN_(DWIN_LCD_PROUI, DWIN_PidTuning(PID_TUNING_TIMEOUT));
  649. TERN_(EXTENSIBLE_UI, ExtUI::onPidTuning(ExtUI::result_t::PID_TUNING_TIMEOUT));
  650. TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_TIMEOUT)));
  651. SERIAL_ECHOPGM(STR_PID_AUTOTUNE);
  652. SERIAL_ECHOLNPGM(STR_PID_TIMEOUT);
  653. break;
  654. }
  655. if (cycles > ncycles && cycles > 2) {
  656. SERIAL_ECHOPGM(STR_PID_AUTOTUNE);
  657. SERIAL_ECHOLNPGM(STR_PID_AUTOTUNE_FINISHED);
  658. TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_AUTOTUNE_DONE)));
  659. #if EITHER(PIDTEMPBED, PIDTEMPCHAMBER)
  660. FSTR_P const estring = GHV(F("chamber"), F("bed"), FPSTR(NUL_STR));
  661. say_default_(); SERIAL_ECHOF(estring); SERIAL_ECHOLNPGM("Kp ", tune_pid.Kp);
  662. say_default_(); SERIAL_ECHOF(estring); SERIAL_ECHOLNPGM("Ki ", tune_pid.Ki);
  663. say_default_(); SERIAL_ECHOF(estring); SERIAL_ECHOLNPGM("Kd ", tune_pid.Kd);
  664. #else
  665. say_default_(); SERIAL_ECHOLNPGM("Kp ", tune_pid.Kp);
  666. say_default_(); SERIAL_ECHOLNPGM("Ki ", tune_pid.Ki);
  667. say_default_(); SERIAL_ECHOLNPGM("Kd ", tune_pid.Kd);
  668. #endif
  669. auto _set_hotend_pid = [](const uint8_t e, const PID_t &in_pid) {
  670. #if ENABLED(PIDTEMP)
  671. PID_PARAM(Kp, e) = in_pid.Kp;
  672. PID_PARAM(Ki, e) = scalePID_i(in_pid.Ki);
  673. PID_PARAM(Kd, e) = scalePID_d(in_pid.Kd);
  674. updatePID();
  675. #else
  676. UNUSED(e); UNUSED(in_pid);
  677. #endif
  678. };
  679. #if ENABLED(PIDTEMPBED)
  680. auto _set_bed_pid = [](const PID_t &in_pid) {
  681. temp_bed.pid.Kp = in_pid.Kp;
  682. temp_bed.pid.Ki = scalePID_i(in_pid.Ki);
  683. temp_bed.pid.Kd = scalePID_d(in_pid.Kd);
  684. };
  685. #endif
  686. #if ENABLED(PIDTEMPCHAMBER)
  687. auto _set_chamber_pid = [](const PID_t &in_pid) {
  688. temp_chamber.pid.Kp = in_pid.Kp;
  689. temp_chamber.pid.Ki = scalePID_i(in_pid.Ki);
  690. temp_chamber.pid.Kd = scalePID_d(in_pid.Kd);
  691. };
  692. #endif
  693. // Use the result? (As with "M303 U1")
  694. if (set_result)
  695. GHV(_set_chamber_pid(tune_pid), _set_bed_pid(tune_pid), _set_hotend_pid(heater_id, tune_pid));
  696. TERN_(PRINTER_EVENT_LEDS, printerEventLEDs.onPidTuningDone(color));
  697. TERN_(EXTENSIBLE_UI, ExtUI::onPidTuning(ExtUI::result_t::PID_DONE));
  698. TERN_(DWIN_LCD_PROUI, DWIN_PidTuning(PID_DONE));
  699. goto EXIT_M303;
  700. }
  701. // Run HAL idle tasks
  702. hal.idletask();
  703. // Run UI update
  704. TERN(DWIN_CREALITY_LCD, DWIN_Update(), ui.update());
  705. }
  706. wait_for_heatup = false;
  707. disable_all_heaters();
  708. TERN_(PRINTER_EVENT_LEDS, printerEventLEDs.onPidTuningDone(color));
  709. TERN_(EXTENSIBLE_UI, ExtUI::onPidTuning(ExtUI::result_t::PID_DONE));
  710. TERN_(DWIN_LCD_PROUI, DWIN_PidTuning(PID_DONE));
  711. EXIT_M303:
  712. TERN_(NO_FAN_SLOWING_IN_PID_TUNING, adaptive_fan_slowing = true);
  713. return;
  714. }
  715. #endif // HAS_PID_HEATING
  716. #if ENABLED(MPCTEMP)
  717. void Temperature::MPC_autotune() {
  718. auto housekeeping = [] (millis_t& ms, celsius_float_t& current_temp, millis_t& next_report_ms) {
  719. ms = millis();
  720. if (updateTemperaturesIfReady()) { // temp sample ready
  721. current_temp = degHotend(active_extruder);
  722. TERN_(HAS_FAN_LOGIC, manage_extruder_fans(ms));
  723. }
  724. if (ELAPSED(ms, next_report_ms)) {
  725. next_report_ms += 1000UL;
  726. print_heater_states(active_extruder);
  727. SERIAL_EOL();
  728. }
  729. hal.idletask();
  730. TERN(DWIN_CREALITY_LCD, DWIN_Update(), ui.update());
  731. if (!wait_for_heatup) {
  732. SERIAL_ECHOPGM(STR_MPC_AUTOTUNE);
  733. SERIAL_ECHOLNPGM(STR_MPC_AUTOTUNE_INTERRUPTED);
  734. return false;
  735. }
  736. return true;
  737. };
  738. struct OnExit {
  739. ~OnExit() {
  740. wait_for_heatup = false;
  741. ui.reset_status();
  742. temp_hotend[active_extruder].target = 0.0f;
  743. temp_hotend[active_extruder].soft_pwm_amount = 0;
  744. #if HAS_FAN
  745. set_fan_speed(ANY(MPC_FAN_0_ALL_HOTENDS, MPC_FAN_0_ACTIVE_HOTEND) ? 0 : active_extruder, 0);
  746. planner.sync_fan_speeds(fan_speed);
  747. #endif
  748. do_z_clearance(MPC_TUNING_END_Z);
  749. }
  750. } on_exit;
  751. SERIAL_ECHOPGM(STR_MPC_AUTOTUNE);
  752. SERIAL_ECHOLNPGM(STR_MPC_AUTOTUNE_START, active_extruder);
  753. MPCHeaterInfo &hotend = temp_hotend[active_extruder];
  754. MPC_t &constants = hotend.constants;
  755. // Move to center of bed, just above bed height and cool with max fan
  756. gcode.home_all_axes(true);
  757. disable_all_heaters();
  758. #if HAS_FAN
  759. zero_fan_speeds();
  760. set_fan_speed(ANY(MPC_FAN_0_ALL_HOTENDS, MPC_FAN_0_ACTIVE_HOTEND) ? 0 : active_extruder, 255);
  761. planner.sync_fan_speeds(fan_speed);
  762. #endif
  763. const xyz_pos_t tuningpos = MPC_TUNING_POS;
  764. do_blocking_move_to(tuningpos);
  765. SERIAL_ECHOLNPGM(STR_MPC_COOLING_TO_AMBIENT);
  766. LCD_MESSAGE(MSG_COOLING);
  767. millis_t ms = millis(), next_report_ms = ms, next_test_ms = ms + 10000UL;
  768. celsius_float_t current_temp = degHotend(active_extruder),
  769. ambient_temp = current_temp;
  770. wait_for_heatup = true;
  771. for (;;) { // Can be interrupted with M108
  772. if (!housekeeping(ms, current_temp, next_report_ms)) return;
  773. if (ELAPSED(ms, next_test_ms)) {
  774. if (current_temp >= ambient_temp) {
  775. ambient_temp = (ambient_temp + current_temp) / 2.0f;
  776. break;
  777. }
  778. ambient_temp = current_temp;
  779. next_test_ms += 10000UL;
  780. }
  781. }
  782. #if HAS_FAN
  783. set_fan_speed(ANY(MPC_FAN_0_ALL_HOTENDS, MPC_FAN_0_ACTIVE_HOTEND) ? 0 : active_extruder, 0);
  784. planner.sync_fan_speeds(fan_speed);
  785. #endif
  786. hotend.modeled_ambient_temp = ambient_temp;
  787. SERIAL_ECHOLNPGM(STR_MPC_HEATING_PAST_200);
  788. LCD_MESSAGE(MSG_HEATING);
  789. hotend.target = 200.0f; // So M105 looks nice
  790. hotend.soft_pwm_amount = MPC_MAX >> 1;
  791. const millis_t heat_start_time = next_test_ms = ms;
  792. celsius_float_t temp_samples[16];
  793. uint8_t sample_count = 0;
  794. uint16_t sample_distance = 1;
  795. float t1_time = 0;
  796. for (;;) { // Can be interrupted with M108
  797. if (!housekeeping(ms, current_temp, next_report_ms)) return;
  798. if (ELAPSED(ms, next_test_ms)) {
  799. // Record samples between 100C and 200C
  800. if (current_temp >= 100.0f) {
  801. // If there are too many samples, space them more widely
  802. if (sample_count == COUNT(temp_samples)) {
  803. for (uint8_t i = 0; i < COUNT(temp_samples) / 2; i++)
  804. temp_samples[i] = temp_samples[i*2];
  805. sample_count /= 2;
  806. sample_distance *= 2;
  807. }
  808. if (sample_count == 0) t1_time = float(ms - heat_start_time) / 1000.0f;
  809. temp_samples[sample_count++] = current_temp;
  810. }
  811. if (current_temp >= 200.0f) break;
  812. next_test_ms += 1000UL * sample_distance;
  813. }
  814. }
  815. hotend.soft_pwm_amount = 0;
  816. // Calculate physical constants from three equally-spaced samples
  817. sample_count = (sample_count + 1) / 2 * 2 - 1;
  818. const float t1 = temp_samples[0],
  819. t2 = temp_samples[(sample_count - 1) >> 1],
  820. t3 = temp_samples[sample_count - 1];
  821. float asymp_temp = (t2 * t2 - t1 * t3) / (2 * t2 - t1 - t3),
  822. block_responsiveness = -log((t2 - asymp_temp) / (t1 - asymp_temp)) / (sample_distance * (sample_count >> 1));
  823. constants.ambient_xfer_coeff_fan0 = constants.heater_power * (MPC_MAX) / 255 / (asymp_temp - ambient_temp);
  824. constants.fan255_adjustment = 0.0f;
  825. constants.block_heat_capacity = constants.ambient_xfer_coeff_fan0 / block_responsiveness;
  826. constants.sensor_responsiveness = block_responsiveness / (1.0f - (ambient_temp - asymp_temp) * exp(-block_responsiveness * t1_time) / (t1 - asymp_temp));
  827. hotend.modeled_block_temp = asymp_temp + (ambient_temp - asymp_temp) * exp(-block_responsiveness * (ms - heat_start_time) / 1000.0f);
  828. hotend.modeled_sensor_temp = current_temp;
  829. // Allow the system to stabilize under MPC, then get a better measure of ambient loss with and without fan
  830. SERIAL_ECHOLNPGM(STR_MPC_MEASURING_AMBIENT, hotend.modeled_block_temp);
  831. LCD_MESSAGE(MSG_MPC_MEASURING_AMBIENT);
  832. hotend.target = hotend.modeled_block_temp;
  833. next_test_ms = ms + MPC_dT * 1000;
  834. constexpr millis_t settle_time = 20000UL, test_duration = 20000UL;
  835. millis_t settle_end_ms = ms + settle_time,
  836. test_end_ms = settle_end_ms + test_duration;
  837. float total_energy_fan0 = 0.0f;
  838. #if HAS_FAN
  839. bool fan0_done = false;
  840. float total_energy_fan255 = 0.0f;
  841. #endif
  842. float last_temp = current_temp;
  843. for (;;) { // Can be interrupted with M108
  844. if (!housekeeping(ms, current_temp, next_report_ms)) return;
  845. if (ELAPSED(ms, next_test_ms)) {
  846. hotend.soft_pwm_amount = (int)get_pid_output_hotend(active_extruder) >> 1;
  847. if (ELAPSED(ms, settle_end_ms) && !ELAPSED(ms, test_end_ms) && TERN1(HAS_FAN, !fan0_done))
  848. total_energy_fan0 += constants.heater_power * hotend.soft_pwm_amount / 127 * MPC_dT + (last_temp - current_temp) * constants.block_heat_capacity;
  849. #if HAS_FAN
  850. else if (ELAPSED(ms, test_end_ms) && !fan0_done) {
  851. set_fan_speed(ANY(MPC_FAN_0_ALL_HOTENDS, MPC_FAN_0_ACTIVE_HOTEND) ? 0 : active_extruder, 255);
  852. planner.sync_fan_speeds(fan_speed);
  853. settle_end_ms = ms + settle_time;
  854. test_end_ms = settle_end_ms + test_duration;
  855. fan0_done = true;
  856. }
  857. else if (ELAPSED(ms, settle_end_ms) && !ELAPSED(ms, test_end_ms))
  858. total_energy_fan255 += constants.heater_power * hotend.soft_pwm_amount / 127 * MPC_dT + (last_temp - current_temp) * constants.block_heat_capacity;
  859. #endif
  860. else if (ELAPSED(ms, test_end_ms)) break;
  861. last_temp = current_temp;
  862. next_test_ms += MPC_dT * 1000;
  863. }
  864. if (!WITHIN(current_temp, t3 - 15.0f, hotend.target + 15.0f)) {
  865. SERIAL_ECHOLNPGM(STR_MPC_TEMPERATURE_ERROR);
  866. break;
  867. }
  868. }
  869. const float power_fan0 = total_energy_fan0 * 1000 / test_duration;
  870. constants.ambient_xfer_coeff_fan0 = power_fan0 / (hotend.target - ambient_temp);
  871. #if HAS_FAN
  872. const float power_fan255 = total_energy_fan255 * 1000 / test_duration,
  873. ambient_xfer_coeff_fan255 = power_fan255 / (hotend.target - ambient_temp);
  874. constants.fan255_adjustment = ambient_xfer_coeff_fan255 - constants.ambient_xfer_coeff_fan0;
  875. #endif
  876. // Calculate a new and better asymptotic temperature and re-evaluate the other constants
  877. asymp_temp = ambient_temp + constants.heater_power * (MPC_MAX) / 255 / constants.ambient_xfer_coeff_fan0;
  878. block_responsiveness = -log((t2 - asymp_temp) / (t1 - asymp_temp)) / (sample_distance * (sample_count >> 1));
  879. constants.block_heat_capacity = constants.ambient_xfer_coeff_fan0 / block_responsiveness;
  880. constants.sensor_responsiveness = block_responsiveness / (1.0f - (ambient_temp - asymp_temp) * exp(-block_responsiveness * t1_time) / (t1 - asymp_temp));
  881. SERIAL_ECHOPGM(STR_MPC_AUTOTUNE);
  882. SERIAL_ECHOLNPGM(STR_MPC_AUTOTUNE_FINISHED);
  883. /* <-- add a slash to enable
  884. SERIAL_ECHOLNPGM("t1_time ", t1_time);
  885. SERIAL_ECHOLNPGM("sample_count ", sample_count);
  886. SERIAL_ECHOLNPGM("sample_distance ", sample_distance);
  887. for (uint8_t i = 0; i < sample_count; i++)
  888. SERIAL_ECHOLNPGM("sample ", i, " : ", temp_samples[i]);
  889. SERIAL_ECHOLNPGM("t1 ", t1, " t2 ", t2, " t3 ", t3);
  890. SERIAL_ECHOLNPGM("asymp_temp ", asymp_temp);
  891. SERIAL_ECHOLNPAIR_F("block_responsiveness ", block_responsiveness, 4);
  892. //*/
  893. SERIAL_ECHOLNPGM("MPC_BLOCK_HEAT_CAPACITY ", constants.block_heat_capacity);
  894. SERIAL_ECHOLNPAIR_F("MPC_SENSOR_RESPONSIVENESS ", constants.sensor_responsiveness, 4);
  895. SERIAL_ECHOLNPAIR_F("MPC_AMBIENT_XFER_COEFF ", constants.ambient_xfer_coeff_fan0, 4);
  896. TERN_(HAS_FAN, SERIAL_ECHOLNPAIR_F("MPC_AMBIENT_XFER_COEFF_FAN255 ", ambient_xfer_coeff_fan255, 4));
  897. }
  898. #endif // MPCTEMP
  899. int16_t Temperature::getHeaterPower(const heater_id_t heater_id) {
  900. switch (heater_id) {
  901. #if HAS_HEATED_BED
  902. case H_BED: return temp_bed.soft_pwm_amount;
  903. #endif
  904. #if HAS_HEATED_CHAMBER
  905. case H_CHAMBER: return temp_chamber.soft_pwm_amount;
  906. #endif
  907. #if HAS_COOLER
  908. case H_COOLER: return temp_cooler.soft_pwm_amount;
  909. #endif
  910. default:
  911. return TERN0(HAS_HOTEND, temp_hotend[heater_id].soft_pwm_amount);
  912. }
  913. }
  914. #define _EFANOVERLAP(A,B) _FANOVERLAP(E##A,B)
  915. #if HAS_AUTO_FAN
  916. #if EXTRUDER_AUTO_FAN_SPEED != 255
  917. #define INIT_E_AUTO_FAN_PIN(P) do{ if (P == FAN1_PIN || P == FAN2_PIN) { SET_PWM(P); SET_FAST_PWM_FREQ(P); } else SET_OUTPUT(P); }while(0)
  918. #else
  919. #define INIT_E_AUTO_FAN_PIN(P) SET_OUTPUT(P)
  920. #endif
  921. #if CHAMBER_AUTO_FAN_SPEED != 255
  922. #define INIT_CHAMBER_AUTO_FAN_PIN(P) do{ if (P == FAN1_PIN || P == FAN2_PIN) { SET_PWM(P); SET_FAST_PWM_FREQ(P); } else SET_OUTPUT(P); }while(0)
  923. #else
  924. #define INIT_CHAMBER_AUTO_FAN_PIN(P) SET_OUTPUT(P)
  925. #endif
  926. #ifndef CHAMBER_FAN_INDEX
  927. #define CHAMBER_FAN_INDEX HOTENDS
  928. #endif
  929. void Temperature::update_autofans() {
  930. #define _EFAN(B,A) _EFANOVERLAP(A,B) ? B :
  931. static const uint8_t fanBit[] PROGMEM = {
  932. 0
  933. #if HAS_MULTI_HOTEND
  934. #define _NEXT_FAN(N) , REPEAT2(N,_EFAN,N) N
  935. RREPEAT_S(1, HOTENDS, _NEXT_FAN)
  936. #endif
  937. #if HAS_AUTO_CHAMBER_FAN
  938. #define _CFAN(B) _FANOVERLAP(CHAMBER,B) ? B :
  939. , REPEAT(HOTENDS,_CFAN) (HOTENDS)
  940. #endif
  941. };
  942. uint8_t fanState = 0;
  943. HOTEND_LOOP() {
  944. if (temp_hotend[e].celsius >= EXTRUDER_AUTO_FAN_TEMPERATURE) {
  945. SBI(fanState, pgm_read_byte(&fanBit[e]));
  946. }
  947. }
  948. #if HAS_AUTO_CHAMBER_FAN
  949. if (temp_chamber.celsius >= CHAMBER_AUTO_FAN_TEMPERATURE)
  950. SBI(fanState, pgm_read_byte(&fanBit[CHAMBER_FAN_INDEX]));
  951. #endif
  952. #if HAS_AUTO_COOLER_FAN
  953. if (temp_cooler.celsius >= COOLER_AUTO_FAN_TEMPERATURE)
  954. SBI(fanState, pgm_read_byte(&fanBit[COOLER_FAN_INDEX]));
  955. #endif
  956. #define _UPDATE_AUTO_FAN(P,D,A) do{ \
  957. if (PWM_PIN(P##_AUTO_FAN_PIN) && A < 255) \
  958. hal.set_pwm_duty(pin_t(P##_AUTO_FAN_PIN), D ? A : 0); \
  959. else \
  960. WRITE(P##_AUTO_FAN_PIN, D); \
  961. }while(0)
  962. uint8_t fanDone = 0;
  963. LOOP_L_N(f, COUNT(fanBit)) {
  964. const uint8_t realFan = pgm_read_byte(&fanBit[f]);
  965. if (TEST(fanDone, realFan)) continue;
  966. const bool fan_on = TEST(fanState, realFan);
  967. switch (f) {
  968. #if ENABLED(AUTO_POWER_CHAMBER_FAN)
  969. case CHAMBER_FAN_INDEX:
  970. chamberfan_speed = fan_on ? CHAMBER_AUTO_FAN_SPEED : 0;
  971. break;
  972. #endif
  973. default:
  974. #if EITHER(AUTO_POWER_E_FANS, HAS_FANCHECK)
  975. autofan_speed[realFan] = fan_on ? EXTRUDER_AUTO_FAN_SPEED : 0;
  976. #endif
  977. break;
  978. }
  979. #if BOTH(HAS_FANCHECK, HAS_PWMFANCHECK)
  980. #define _AUTOFAN_SPEED() fan_check.is_measuring() ? 255 : EXTRUDER_AUTO_FAN_SPEED
  981. #else
  982. #define _AUTOFAN_SPEED() EXTRUDER_AUTO_FAN_SPEED
  983. #endif
  984. #define _AUTOFAN_CASE(N) case N: _UPDATE_AUTO_FAN(E##N, fan_on, _AUTOFAN_SPEED()); break
  985. switch (f) {
  986. #if HAS_AUTO_FAN_0
  987. _AUTOFAN_CASE(0);
  988. #endif
  989. #if HAS_AUTO_FAN_1
  990. _AUTOFAN_CASE(1);
  991. #endif
  992. #if HAS_AUTO_FAN_2
  993. _AUTOFAN_CASE(2);
  994. #endif
  995. #if HAS_AUTO_FAN_3
  996. _AUTOFAN_CASE(3);
  997. #endif
  998. #if HAS_AUTO_FAN_4
  999. _AUTOFAN_CASE(4);
  1000. #endif
  1001. #if HAS_AUTO_FAN_5
  1002. _AUTOFAN_CASE(5);
  1003. #endif
  1004. #if HAS_AUTO_FAN_6
  1005. _AUTOFAN_CASE(6);
  1006. #endif
  1007. #if HAS_AUTO_FAN_7
  1008. _AUTOFAN_CASE(7);
  1009. #endif
  1010. #if HAS_AUTO_CHAMBER_FAN && !AUTO_CHAMBER_IS_E
  1011. case CHAMBER_FAN_INDEX: _UPDATE_AUTO_FAN(CHAMBER, fan_on, CHAMBER_AUTO_FAN_SPEED); break;
  1012. #endif
  1013. }
  1014. SBI(fanDone, realFan);
  1015. }
  1016. }
  1017. #endif // HAS_AUTO_FAN
  1018. //
  1019. // Temperature Error Handlers
  1020. //
  1021. inline void loud_kill(FSTR_P const lcd_msg, const heater_id_t heater_id) {
  1022. marlin_state = MF_KILLED;
  1023. thermalManager.disable_all_heaters();
  1024. #if HAS_BEEPER
  1025. for (uint8_t i = 20; i--;) {
  1026. hal.watchdog_refresh();
  1027. buzzer.click(25);
  1028. delay(80);
  1029. hal.watchdog_refresh();
  1030. }
  1031. buzzer.on();
  1032. #endif
  1033. #if ENABLED(NOZZLE_PARK_FEATURE)
  1034. if (!homing_needed_error()) {
  1035. nozzle.park(0);
  1036. planner.synchronize();
  1037. }
  1038. #endif
  1039. kill(lcd_msg, HEATER_FSTR(heater_id));
  1040. }
  1041. void Temperature::_temp_error(const heater_id_t heater_id, FSTR_P const serial_msg, FSTR_P const lcd_msg) {
  1042. static uint8_t killed = 0;
  1043. if (IsRunning() && TERN1(BOGUS_TEMPERATURE_GRACE_PERIOD, killed == 2)) {
  1044. SERIAL_ERROR_START();
  1045. SERIAL_ECHOF(serial_msg);
  1046. SERIAL_ECHOPGM(STR_STOPPED_HEATER);
  1047. heater_id_t real_heater_id = heater_id;
  1048. #if HAS_TEMP_REDUNDANT
  1049. if (heater_id == H_REDUNDANT) {
  1050. SERIAL_ECHOPGM(STR_REDUNDANT); // print redundant and cascade to print target, too.
  1051. real_heater_id = (heater_id_t)HEATER_ID(TEMP_SENSOR_REDUNDANT_TARGET);
  1052. }
  1053. #endif
  1054. switch (real_heater_id) {
  1055. OPTCODE(HAS_TEMP_COOLER, case H_COOLER: SERIAL_ECHOPGM(STR_COOLER); break)
  1056. OPTCODE(HAS_TEMP_PROBE, case H_PROBE: SERIAL_ECHOPGM(STR_PROBE); break)
  1057. OPTCODE(HAS_TEMP_BOARD, case H_BOARD: SERIAL_ECHOPGM(STR_MOTHERBOARD); break)
  1058. OPTCODE(HAS_TEMP_CHAMBER, case H_CHAMBER: SERIAL_ECHOPGM(STR_HEATER_CHAMBER); break)
  1059. OPTCODE(HAS_TEMP_BED, case H_BED: SERIAL_ECHOPGM(STR_HEATER_BED); break)
  1060. default:
  1061. if (real_heater_id >= 0)
  1062. SERIAL_ECHOLNPGM("E", real_heater_id);
  1063. }
  1064. SERIAL_EOL();
  1065. }
  1066. disable_all_heaters(); // always disable (even for bogus temp)
  1067. hal.watchdog_refresh();
  1068. #if BOGUS_TEMPERATURE_GRACE_PERIOD
  1069. const millis_t ms = millis();
  1070. static millis_t expire_ms;
  1071. switch (killed) {
  1072. case 0:
  1073. expire_ms = ms + BOGUS_TEMPERATURE_GRACE_PERIOD;
  1074. ++killed;
  1075. break;
  1076. case 1:
  1077. if (ELAPSED(ms, expire_ms)) ++killed;
  1078. break;
  1079. case 2:
  1080. loud_kill(lcd_msg, heater_id);
  1081. ++killed;
  1082. break;
  1083. }
  1084. #elif defined(BOGUS_TEMPERATURE_GRACE_PERIOD)
  1085. UNUSED(killed);
  1086. #else
  1087. if (!killed) { killed = 1; loud_kill(lcd_msg, heater_id); }
  1088. #endif
  1089. }
  1090. void Temperature::max_temp_error(const heater_id_t heater_id) {
  1091. #if HAS_DWIN_E3V2_BASIC && (HAS_HOTEND || HAS_HEATED_BED)
  1092. DWIN_Popup_Temperature(1);
  1093. #endif
  1094. _temp_error(heater_id, F(STR_T_MAXTEMP), GET_TEXT_F(MSG_ERR_MAXTEMP));
  1095. }
  1096. void Temperature::min_temp_error(const heater_id_t heater_id) {
  1097. #if HAS_DWIN_E3V2_BASIC && (HAS_HOTEND || HAS_HEATED_BED)
  1098. DWIN_Popup_Temperature(0);
  1099. #endif
  1100. _temp_error(heater_id, F(STR_T_MINTEMP), GET_TEXT_F(MSG_ERR_MINTEMP));
  1101. }
  1102. #if ANY(PID_DEBUG, PID_BED_DEBUG, PID_CHAMBER_DEBUG)
  1103. #define HAS_PID_DEBUG 1
  1104. bool Temperature::pid_debug_flag; // = false
  1105. #endif
  1106. #if HAS_PID_HEATING
  1107. template<typename TT, int MIN_POW, int MAX_POW>
  1108. class PIDRunner {
  1109. public:
  1110. TT &tempinfo;
  1111. __typeof__(TT::pid) work_pid{0};
  1112. float temp_iState = 0, temp_dState = 0;
  1113. bool pid_reset = true;
  1114. PIDRunner(TT &t) : tempinfo(t) { }
  1115. float get_pid_output() {
  1116. #if ENABLED(PID_OPENLOOP)
  1117. return constrain(tempinfo.target, 0, MAX_POW);
  1118. #else // !PID_OPENLOOP
  1119. const float pid_error = tempinfo.target - tempinfo.celsius;
  1120. if (!tempinfo.target || pid_error < -(PID_FUNCTIONAL_RANGE)) {
  1121. pid_reset = true;
  1122. return 0;
  1123. }
  1124. else if (pid_error > PID_FUNCTIONAL_RANGE) {
  1125. pid_reset = true;
  1126. return MAX_POW;
  1127. }
  1128. if (pid_reset) {
  1129. pid_reset = false;
  1130. temp_iState = 0.0;
  1131. work_pid.Kd = 0.0;
  1132. }
  1133. const float max_power_over_i_gain = float(MAX_POW) / tempinfo.pid.Ki - float(MIN_POW);
  1134. temp_iState = constrain(temp_iState + pid_error, 0, max_power_over_i_gain);
  1135. work_pid.Kp = tempinfo.pid.Kp * pid_error;
  1136. work_pid.Ki = tempinfo.pid.Ki * temp_iState;
  1137. work_pid.Kd = work_pid.Kd + PID_K2 * (tempinfo.pid.Kd * (temp_dState - tempinfo.celsius) - work_pid.Kd);
  1138. temp_dState = tempinfo.celsius;
  1139. return constrain(work_pid.Kp + work_pid.Ki + work_pid.Kd + float(MIN_POW), 0, MAX_POW);
  1140. #endif // !PID_OPENLOOP
  1141. }
  1142. FORCE_INLINE void debug(const_celsius_float_t c, const_float_t pid_out, FSTR_P const name=nullptr, const int8_t index=-1) {
  1143. if (TERN0(HAS_PID_DEBUG, thermalManager.pid_debug_flag)) {
  1144. SERIAL_ECHO_START();
  1145. if (name) SERIAL_ECHOLNF(name);
  1146. if (index >= 0) SERIAL_ECHO(index);
  1147. SERIAL_ECHOLNPGM(
  1148. STR_PID_DEBUG_INPUT, c,
  1149. STR_PID_DEBUG_OUTPUT, pid_out
  1150. #if DISABLED(PID_OPENLOOP)
  1151. , "pTerm", work_pid.Kp, "iTerm", work_pid.Ki, "dTerm", work_pid.Kd
  1152. #endif
  1153. );
  1154. }
  1155. }
  1156. };
  1157. #endif // HAS_PID_HEATING
  1158. #if HAS_HOTEND
  1159. float Temperature::get_pid_output_hotend(const uint8_t E_NAME) {
  1160. const uint8_t ee = HOTEND_INDEX;
  1161. #if ENABLED(PIDTEMP)
  1162. typedef PIDRunner<hotend_info_t, 0, PID_MAX> PIDRunnerHotend;
  1163. static PIDRunnerHotend hotend_pid[HOTENDS] = {
  1164. #define _HOTENDPID(E) temp_hotend[E],
  1165. REPEAT(HOTENDS, _HOTENDPID)
  1166. };
  1167. const float pid_output = hotend_pid[ee].get_pid_output();
  1168. #if ENABLED(PID_DEBUG)
  1169. if (ee == active_extruder)
  1170. hotend_pid[ee].debug(temp_hotend[ee].celsius, pid_output, F("E"), ee);
  1171. #endif
  1172. #elif ENABLED(MPCTEMP)
  1173. MPCHeaterInfo &hotend = temp_hotend[ee];
  1174. MPC_t &constants = hotend.constants;
  1175. // At startup, initialize modeled temperatures
  1176. if (isnan(hotend.modeled_block_temp)) {
  1177. hotend.modeled_ambient_temp = min(30.0f, hotend.celsius); // Cap initial value at reasonable max room temperature of 30C
  1178. hotend.modeled_block_temp = hotend.modeled_sensor_temp = hotend.celsius;
  1179. }
  1180. #if HOTENDS == 1
  1181. constexpr bool this_hotend = true;
  1182. #else
  1183. const bool this_hotend = (ee == active_extruder);
  1184. #endif
  1185. float ambient_xfer_coeff = constants.ambient_xfer_coeff_fan0;
  1186. #if ENABLED(MPC_INCLUDE_FAN)
  1187. const uint8_t fan_index = ANY(MPC_FAN_0_ACTIVE_HOTEND, MPC_FAN_0_ALL_HOTENDS) ? 0 : ee;
  1188. const float fan_fraction = TERN_(MPC_FAN_0_ACTIVE_HOTEND, !this_hotend ? 0.0f : ) fan_speed[fan_index] * RECIPROCAL(255);
  1189. ambient_xfer_coeff += fan_fraction * constants.fan255_adjustment;
  1190. #endif
  1191. if (this_hotend) {
  1192. const int32_t e_position = stepper.position(E_AXIS);
  1193. const float e_speed = (e_position - mpc_e_position) * planner.mm_per_step[E_AXIS] / MPC_dT;
  1194. // The position can appear to make big jumps when, e.g. homing
  1195. if (fabs(e_speed) > planner.settings.max_feedrate_mm_s[E_AXIS])
  1196. mpc_e_position = e_position;
  1197. else if (e_speed > 0.0f) { // Ignore retract/recover moves
  1198. ambient_xfer_coeff += e_speed * constants.filament_heat_capacity_permm;
  1199. mpc_e_position = e_position;
  1200. }
  1201. }
  1202. // Update the modeled temperatures
  1203. float blocktempdelta = hotend.soft_pwm_amount * constants.heater_power * (MPC_dT / 127) / constants.block_heat_capacity;
  1204. blocktempdelta += (hotend.modeled_ambient_temp - hotend.modeled_block_temp) * ambient_xfer_coeff * MPC_dT / constants.block_heat_capacity;
  1205. hotend.modeled_block_temp += blocktempdelta;
  1206. const float sensortempdelta = (hotend.modeled_block_temp - hotend.modeled_sensor_temp) * (constants.sensor_responsiveness * MPC_dT);
  1207. hotend.modeled_sensor_temp += sensortempdelta;
  1208. // Any delta between hotend.modeled_sensor_temp and hotend.celsius is either model
  1209. // error diverging slowly or (fast) noise. Slowly correct towards this temperature and noise will average out.
  1210. const float delta_to_apply = (hotend.celsius - hotend.modeled_sensor_temp) * (MPC_SMOOTHING_FACTOR);
  1211. hotend.modeled_block_temp += delta_to_apply;
  1212. hotend.modeled_sensor_temp += delta_to_apply;
  1213. // Only correct ambient when close to steady state (output power is not clipped or asymptotic temperature is reached)
  1214. if (WITHIN(hotend.soft_pwm_amount, 1, 126) || fabs(blocktempdelta + delta_to_apply) < (MPC_STEADYSTATE * MPC_dT))
  1215. hotend.modeled_ambient_temp += delta_to_apply > 0.f ? max(delta_to_apply, MPC_MIN_AMBIENT_CHANGE * MPC_dT) : min(delta_to_apply, -MPC_MIN_AMBIENT_CHANGE * MPC_dT);
  1216. float power = 0.0;
  1217. if (hotend.target != 0 && TERN1(HEATER_IDLE_HANDLER, !heater_idle[ee].timed_out)) {
  1218. // Plan power level to get to target temperature in 2 seconds
  1219. power = (hotend.target - hotend.modeled_block_temp) * constants.block_heat_capacity / 2.0f;
  1220. power -= (hotend.modeled_ambient_temp - hotend.modeled_block_temp) * ambient_xfer_coeff;
  1221. }
  1222. float pid_output = power * 254.0f / constants.heater_power + 1.0f; // Ensure correct quantization into a range of 0 to 127
  1223. pid_output = constrain(pid_output, 0, MPC_MAX);
  1224. /* <-- add a slash to enable
  1225. static uint32_t nexttime = millis() + 1000;
  1226. if (ELAPSED(millis(), nexttime)) {
  1227. nexttime += 1000;
  1228. SERIAL_ECHOLNPGM("block temp ", hotend.modeled_block_temp,
  1229. ", celsius ", hotend.celsius,
  1230. ", blocktempdelta ", blocktempdelta,
  1231. ", delta_to_apply ", delta_to_apply,
  1232. ", ambient ", hotend.modeled_ambient_temp,
  1233. ", power ", power,
  1234. ", pid_output ", pid_output,
  1235. ", pwm ", (int)pid_output >> 1);
  1236. }
  1237. //*/
  1238. #else // No PID or MPC enabled
  1239. const bool is_idling = TERN0(HEATER_IDLE_HANDLER, heater_idle[ee].timed_out);
  1240. const float pid_output = (!is_idling && temp_hotend[ee].is_below_target()) ? BANG_MAX : 0;
  1241. #endif
  1242. return pid_output;
  1243. }
  1244. #endif // HAS_HOTEND
  1245. #if ENABLED(PIDTEMPBED)
  1246. float Temperature::get_pid_output_bed() {
  1247. static PIDRunner<bed_info_t, MIN_BED_POWER, MAX_BED_POWER> bed_pid(temp_bed);
  1248. const float pid_output = bed_pid.get_pid_output();
  1249. TERN_(PID_BED_DEBUG, bed_pid.debug(temp_bed.celsius, pid_output, F("(Bed)")));
  1250. return pid_output;
  1251. }
  1252. #endif // PIDTEMPBED
  1253. #if ENABLED(PIDTEMPCHAMBER)
  1254. float Temperature::get_pid_output_chamber() {
  1255. static PIDRunner<chamber_info_t, MIN_CHAMBER_POWER, MAX_CHAMBER_POWER> chamber_pid(temp_chamber);
  1256. const float pid_output = chamber_pid.get_pid_output();
  1257. TERN_(PID_CHAMBER_DEBUG, chamber_pid.debug(temp_chamber.celsius, pid_output, F("(Chamber)")));
  1258. return pid_output;
  1259. }
  1260. #endif // PIDTEMPCHAMBER
  1261. #if HAS_HOTEND
  1262. void Temperature::manage_hotends(const millis_t &ms) {
  1263. HOTEND_LOOP() {
  1264. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  1265. if (degHotend(e) > temp_range[e].maxtemp) max_temp_error((heater_id_t)e);
  1266. #endif
  1267. TERN_(HEATER_IDLE_HANDLER, heater_idle[e].update(ms));
  1268. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  1269. // Check for thermal runaway
  1270. tr_state_machine[e].run(temp_hotend[e].celsius, temp_hotend[e].target, (heater_id_t)e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS);
  1271. #endif
  1272. temp_hotend[e].soft_pwm_amount = (temp_hotend[e].celsius > temp_range[e].mintemp || is_preheating(e)) && temp_hotend[e].celsius < temp_range[e].maxtemp ? (int)get_pid_output_hotend(e) >> 1 : 0;
  1273. #if WATCH_HOTENDS
  1274. // Make sure temperature is increasing
  1275. if (watch_hotend[e].elapsed(ms)) { // Enabled and time to check?
  1276. if (watch_hotend[e].check(degHotend(e))) // Increased enough?
  1277. start_watching_hotend(e); // If temp reached, turn off elapsed check
  1278. else {
  1279. TERN_(HAS_DWIN_E3V2_BASIC, DWIN_Popup_Temperature(0));
  1280. _temp_error((heater_id_t)e, FPSTR(str_t_heating_failed), GET_TEXT_F(MSG_HEATING_FAILED_LCD));
  1281. }
  1282. }
  1283. #endif
  1284. } // HOTEND_LOOP
  1285. }
  1286. #endif // HAS_HOTEND
  1287. #if HAS_HEATED_BED
  1288. void Temperature::manage_heated_bed(const millis_t &ms) {
  1289. #if ENABLED(THERMAL_PROTECTION_BED)
  1290. if (degBed() > BED_MAXTEMP) max_temp_error(H_BED);
  1291. #endif
  1292. #if WATCH_BED
  1293. // Make sure temperature is increasing
  1294. if (watch_bed.elapsed(ms)) { // Time to check the bed?
  1295. if (watch_bed.check(degBed())) // Increased enough?
  1296. start_watching_bed(); // If temp reached, turn off elapsed check
  1297. else {
  1298. TERN_(HAS_DWIN_E3V2_BASIC, DWIN_Popup_Temperature(0));
  1299. _temp_error(H_BED, FPSTR(str_t_heating_failed), GET_TEXT_F(MSG_HEATING_FAILED_LCD));
  1300. }
  1301. }
  1302. #endif // WATCH_BED
  1303. #if BOTH(PROBING_HEATERS_OFF, BED_LIMIT_SWITCHING)
  1304. #define PAUSE_CHANGE_REQD 1
  1305. #endif
  1306. #if PAUSE_CHANGE_REQD
  1307. static bool last_pause_state;
  1308. #endif
  1309. do {
  1310. #if DISABLED(PIDTEMPBED)
  1311. if (PENDING(ms, next_bed_check_ms)
  1312. && TERN1(PAUSE_CHANGE_REQD, paused_for_probing == last_pause_state)
  1313. ) break;
  1314. next_bed_check_ms = ms + BED_CHECK_INTERVAL;
  1315. TERN_(PAUSE_CHANGE_REQD, last_pause_state = paused_for_probing);
  1316. #endif
  1317. TERN_(HEATER_IDLE_HANDLER, heater_idle[IDLE_INDEX_BED].update(ms));
  1318. #if ENABLED(THERMAL_PROTECTION_BED)
  1319. tr_state_machine[RUNAWAY_IND_BED].run(temp_bed.celsius, temp_bed.target, H_BED, THERMAL_PROTECTION_BED_PERIOD, THERMAL_PROTECTION_BED_HYSTERESIS);
  1320. #endif
  1321. #if HEATER_IDLE_HANDLER
  1322. if (heater_idle[IDLE_INDEX_BED].timed_out) {
  1323. temp_bed.soft_pwm_amount = 0;
  1324. if (DISABLED(PIDTEMPBED)) WRITE_HEATER_BED(LOW);
  1325. }
  1326. else
  1327. #endif
  1328. {
  1329. #if ENABLED(PIDTEMPBED)
  1330. temp_bed.soft_pwm_amount = WITHIN(temp_bed.celsius, BED_MINTEMP, BED_MAXTEMP) ? (int)get_pid_output_bed() >> 1 : 0;
  1331. #else
  1332. // Check if temperature is within the correct band
  1333. if (WITHIN(temp_bed.celsius, BED_MINTEMP, BED_MAXTEMP)) {
  1334. #if ENABLED(BED_LIMIT_SWITCHING)
  1335. if (temp_bed.celsius >= temp_bed.target + BED_HYSTERESIS)
  1336. temp_bed.soft_pwm_amount = 0;
  1337. else if (temp_bed.is_below_target(-(BED_HYSTERESIS) + 1))
  1338. temp_bed.soft_pwm_amount = MAX_BED_POWER >> 1;
  1339. #else // !PIDTEMPBED && !BED_LIMIT_SWITCHING
  1340. temp_bed.soft_pwm_amount = temp_bed.is_below_target() ? MAX_BED_POWER >> 1 : 0;
  1341. #endif
  1342. }
  1343. else {
  1344. temp_bed.soft_pwm_amount = 0;
  1345. WRITE_HEATER_BED(LOW);
  1346. }
  1347. #endif
  1348. }
  1349. } while (false);
  1350. }
  1351. #endif // HAS_HEATED_BED
  1352. #if HAS_HEATED_CHAMBER
  1353. void Temperature::manage_heated_chamber(const millis_t &ms) {
  1354. #ifndef CHAMBER_CHECK_INTERVAL
  1355. #define CHAMBER_CHECK_INTERVAL 1000UL
  1356. #endif
  1357. #if ENABLED(THERMAL_PROTECTION_CHAMBER)
  1358. if (degChamber() > CHAMBER_MAXTEMP) max_temp_error(H_CHAMBER);
  1359. #endif
  1360. #if WATCH_CHAMBER
  1361. // Make sure temperature is increasing
  1362. if (watch_chamber.elapsed(ms)) { // Time to check the chamber?
  1363. if (watch_chamber.check(degChamber())) // Increased enough? Error below.
  1364. start_watching_chamber(); // If temp reached, turn off elapsed check.
  1365. else
  1366. _temp_error(H_CHAMBER, FPSTR(str_t_heating_failed), GET_TEXT_F(MSG_HEATING_FAILED_LCD));
  1367. }
  1368. #endif
  1369. #if EITHER(CHAMBER_FAN, CHAMBER_VENT) || DISABLED(PIDTEMPCHAMBER)
  1370. static bool flag_chamber_excess_heat; // = false;
  1371. #endif
  1372. #if EITHER(CHAMBER_FAN, CHAMBER_VENT)
  1373. static bool flag_chamber_off; // = false
  1374. if (temp_chamber.target > CHAMBER_MINTEMP) {
  1375. flag_chamber_off = false;
  1376. #if ENABLED(CHAMBER_FAN)
  1377. int16_t fan_chamber_pwm;
  1378. #if CHAMBER_FAN_MODE == 0
  1379. fan_chamber_pwm = CHAMBER_FAN_BASE;
  1380. #elif CHAMBER_FAN_MODE == 1
  1381. fan_chamber_pwm = (temp_chamber.celsius > temp_chamber.target) ? (CHAMBER_FAN_BASE) + (CHAMBER_FAN_FACTOR) * (temp_chamber.celsius - temp_chamber.target) : 0;
  1382. #elif CHAMBER_FAN_MODE == 2
  1383. fan_chamber_pwm = (CHAMBER_FAN_BASE) + (CHAMBER_FAN_FACTOR) * ABS(temp_chamber.celsius - temp_chamber.target);
  1384. if (temp_chamber.soft_pwm_amount)
  1385. fan_chamber_pwm += (CHAMBER_FAN_FACTOR) * 2;
  1386. #elif CHAMBER_FAN_MODE == 3
  1387. fan_chamber_pwm = CHAMBER_FAN_BASE + _MAX((CHAMBER_FAN_FACTOR) * (temp_chamber.celsius - temp_chamber.target), 0);
  1388. #endif
  1389. NOMORE(fan_chamber_pwm, 255);
  1390. set_fan_speed(CHAMBER_FAN_INDEX, fan_chamber_pwm);
  1391. #endif
  1392. #if ENABLED(CHAMBER_VENT)
  1393. #ifndef MIN_COOLING_SLOPE_TIME_CHAMBER_VENT
  1394. #define MIN_COOLING_SLOPE_TIME_CHAMBER_VENT 20
  1395. #endif
  1396. #ifndef MIN_COOLING_SLOPE_DEG_CHAMBER_VENT
  1397. #define MIN_COOLING_SLOPE_DEG_CHAMBER_VENT 1.5
  1398. #endif
  1399. if (!flag_chamber_excess_heat && temp_chamber.celsius - temp_chamber.target >= HIGH_EXCESS_HEAT_LIMIT) {
  1400. // Open vent after MIN_COOLING_SLOPE_TIME_CHAMBER_VENT seconds if the
  1401. // temperature didn't drop at least MIN_COOLING_SLOPE_DEG_CHAMBER_VENT
  1402. if (next_cool_check_ms_2 == 0 || ELAPSED(ms, next_cool_check_ms_2)) {
  1403. if (temp_chamber.celsius - old_temp > MIN_COOLING_SLOPE_DEG_CHAMBER_VENT)
  1404. flag_chamber_excess_heat = true; // the bed is heating the chamber too much
  1405. next_cool_check_ms_2 = ms + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_CHAMBER_VENT);
  1406. old_temp = temp_chamber.celsius;
  1407. }
  1408. }
  1409. else {
  1410. next_cool_check_ms_2 = 0;
  1411. old_temp = 9999;
  1412. }
  1413. if (flag_chamber_excess_heat && (temp_chamber.target - temp_chamber.celsius >= LOW_EXCESS_HEAT_LIMIT))
  1414. flag_chamber_excess_heat = false;
  1415. #endif
  1416. }
  1417. else if (!flag_chamber_off) {
  1418. #if ENABLED(CHAMBER_FAN)
  1419. flag_chamber_off = true;
  1420. set_fan_speed(CHAMBER_FAN_INDEX, 0);
  1421. #endif
  1422. #if ENABLED(CHAMBER_VENT)
  1423. flag_chamber_excess_heat = false;
  1424. servo[CHAMBER_VENT_SERVO_NR].move(90);
  1425. #endif
  1426. }
  1427. #endif
  1428. #if ENABLED(PIDTEMPCHAMBER)
  1429. // PIDTEMPCHAMBER doesn't support a CHAMBER_VENT yet.
  1430. temp_chamber.soft_pwm_amount = WITHIN(temp_chamber.celsius, CHAMBER_MINTEMP, CHAMBER_MAXTEMP) ? (int)get_pid_output_chamber() >> 1 : 0;
  1431. #else
  1432. if (ELAPSED(ms, next_chamber_check_ms)) {
  1433. next_chamber_check_ms = ms + CHAMBER_CHECK_INTERVAL;
  1434. if (WITHIN(temp_chamber.celsius, CHAMBER_MINTEMP, CHAMBER_MAXTEMP)) {
  1435. if (flag_chamber_excess_heat) {
  1436. temp_chamber.soft_pwm_amount = 0;
  1437. #if ENABLED(CHAMBER_VENT)
  1438. if (!flag_chamber_off) servo[CHAMBER_VENT_SERVO_NR].move(temp_chamber.is_below_target() ? 0 : 90);
  1439. #endif
  1440. }
  1441. else {
  1442. #if ENABLED(CHAMBER_LIMIT_SWITCHING)
  1443. if (temp_chamber.celsius >= temp_chamber.target + TEMP_CHAMBER_HYSTERESIS)
  1444. temp_chamber.soft_pwm_amount = 0;
  1445. else if (temp_chamber.is_below_target(-(TEMP_CHAMBER_HYSTERESIS) + 1))
  1446. temp_chamber.soft_pwm_amount = (MAX_CHAMBER_POWER) >> 1;
  1447. #else
  1448. temp_chamber.soft_pwm_amount = temp_chamber.is_below_target() ? (MAX_CHAMBER_POWER) >> 1 : 0;
  1449. #endif
  1450. #if ENABLED(CHAMBER_VENT)
  1451. if (!flag_chamber_off) servo[CHAMBER_VENT_SERVO_NR].move(0);
  1452. #endif
  1453. }
  1454. }
  1455. else {
  1456. temp_chamber.soft_pwm_amount = 0;
  1457. WRITE_HEATER_CHAMBER(LOW);
  1458. }
  1459. }
  1460. #if ENABLED(THERMAL_PROTECTION_CHAMBER)
  1461. tr_state_machine[RUNAWAY_IND_CHAMBER].run(temp_chamber.celsius, temp_chamber.target, H_CHAMBER, THERMAL_PROTECTION_CHAMBER_PERIOD, THERMAL_PROTECTION_CHAMBER_HYSTERESIS);
  1462. #endif
  1463. #endif
  1464. }
  1465. #endif // HAS_HEATED_CHAMBER
  1466. #if HAS_COOLER
  1467. void Temperature::manage_cooler(const millis_t &ms) {
  1468. #ifndef COOLER_CHECK_INTERVAL
  1469. #define COOLER_CHECK_INTERVAL 2000UL
  1470. #endif
  1471. #if ENABLED(THERMAL_PROTECTION_COOLER)
  1472. if (degCooler() > COOLER_MAXTEMP) max_temp_error(H_COOLER);
  1473. #endif
  1474. #if WATCH_COOLER
  1475. // Make sure temperature is decreasing
  1476. if (watch_cooler.elapsed(ms)) { // Time to check the cooler?
  1477. if (degCooler() > watch_cooler.target) // Failed to decrease enough?
  1478. _temp_error(H_COOLER, GET_TEXT_F(MSG_COOLING_FAILED), GET_TEXT_F(MSG_COOLING_FAILED));
  1479. else
  1480. start_watching_cooler(); // Start again if the target is still far off
  1481. }
  1482. #endif
  1483. static bool flag_cooler_state; // = false
  1484. if (cooler.enabled) {
  1485. flag_cooler_state = true; // used to allow M106 fan control when cooler is disabled
  1486. if (temp_cooler.target == 0) temp_cooler.target = COOLER_MIN_TARGET;
  1487. if (ELAPSED(ms, next_cooler_check_ms)) {
  1488. next_cooler_check_ms = ms + COOLER_CHECK_INTERVAL;
  1489. if (temp_cooler.celsius > temp_cooler.target) {
  1490. temp_cooler.soft_pwm_amount = temp_cooler.celsius > temp_cooler.target ? MAX_COOLER_POWER : 0;
  1491. flag_cooler_state = temp_cooler.soft_pwm_amount > 0 ? true : false; // used to allow M106 fan control when cooler is disabled
  1492. #if ENABLED(COOLER_FAN)
  1493. int16_t fan_cooler_pwm = (COOLER_FAN_BASE) + (COOLER_FAN_FACTOR) * ABS(temp_cooler.celsius - temp_cooler.target);
  1494. NOMORE(fan_cooler_pwm, 255);
  1495. set_fan_speed(COOLER_FAN_INDEX, fan_cooler_pwm); // Set cooler fan pwm
  1496. cooler_fan_flush_ms = ms + 5000;
  1497. #endif
  1498. }
  1499. else {
  1500. temp_cooler.soft_pwm_amount = 0;
  1501. #if ENABLED(COOLER_FAN)
  1502. set_fan_speed(COOLER_FAN_INDEX, temp_cooler.celsius > temp_cooler.target - 2 ? COOLER_FAN_BASE : 0);
  1503. #endif
  1504. WRITE_HEATER_COOLER(LOW);
  1505. }
  1506. }
  1507. }
  1508. else {
  1509. temp_cooler.soft_pwm_amount = 0;
  1510. if (flag_cooler_state) {
  1511. flag_cooler_state = false;
  1512. thermalManager.set_fan_speed(COOLER_FAN_INDEX, 0);
  1513. }
  1514. WRITE_HEATER_COOLER(LOW);
  1515. }
  1516. #if ENABLED(THERMAL_PROTECTION_COOLER)
  1517. tr_state_machine[RUNAWAY_IND_COOLER].run(temp_cooler.celsius, temp_cooler.target, H_COOLER, THERMAL_PROTECTION_COOLER_PERIOD, THERMAL_PROTECTION_COOLER_HYSTERESIS);
  1518. #endif
  1519. }
  1520. #endif // HAS_COOLER
  1521. /**
  1522. * Manage heating activities for extruder hot-ends and a heated bed
  1523. * - Acquire updated temperature readings
  1524. * - Also resets the watchdog timer
  1525. * - Invoke thermal runaway protection
  1526. * - Manage extruder auto-fan
  1527. * - Apply filament width to the extrusion rate (may move)
  1528. * - Update the heated bed PID output value
  1529. */
  1530. void Temperature::task() {
  1531. if (marlin_state == MF_INITIALIZING) return hal.watchdog_refresh(); // If Marlin isn't started, at least reset the watchdog!
  1532. static bool no_reentry = false; // Prevent recursion
  1533. if (no_reentry) return;
  1534. REMEMBER(mh, no_reentry, true);
  1535. #if ENABLED(EMERGENCY_PARSER)
  1536. if (emergency_parser.killed_by_M112) kill(FPSTR(M112_KILL_STR), nullptr, true);
  1537. if (emergency_parser.quickstop_by_M410) {
  1538. emergency_parser.quickstop_by_M410 = false; // quickstop_stepper may call idle so clear this now!
  1539. quickstop_stepper();
  1540. }
  1541. #endif
  1542. if (!updateTemperaturesIfReady()) return; // Will also reset the watchdog if temperatures are ready
  1543. #if DISABLED(IGNORE_THERMOCOUPLE_ERRORS)
  1544. #if TEMP_SENSOR_0_IS_MAX_TC
  1545. if (degHotend(0) > _MIN(HEATER_0_MAXTEMP, TEMP_SENSOR_0_MAX_TC_TMAX - 1.0)) max_temp_error(H_E0);
  1546. if (degHotend(0) < _MAX(HEATER_0_MINTEMP, TEMP_SENSOR_0_MAX_TC_TMIN + .01)) min_temp_error(H_E0);
  1547. #endif
  1548. #if TEMP_SENSOR_1_IS_MAX_TC
  1549. if (degHotend(1) > _MIN(HEATER_1_MAXTEMP, TEMP_SENSOR_1_MAX_TC_TMAX - 1.0)) max_temp_error(H_E1);
  1550. if (degHotend(1) < _MAX(HEATER_1_MINTEMP, TEMP_SENSOR_1_MAX_TC_TMIN + .01)) min_temp_error(H_E1);
  1551. #endif
  1552. #if TEMP_SENSOR_REDUNDANT_IS_MAX_TC
  1553. if (degRedundant() > TEMP_SENSOR_REDUNDANT_MAX_TC_TMAX - 1.0) max_temp_error(H_REDUNDANT);
  1554. if (degRedundant() < TEMP_SENSOR_REDUNDANT_MAX_TC_TMIN + .01) min_temp_error(H_REDUNDANT);
  1555. #endif
  1556. #else
  1557. #warning "Safety Alert! Disable IGNORE_THERMOCOUPLE_ERRORS for the final build!"
  1558. #endif
  1559. const millis_t ms = millis();
  1560. // Handle Hotend Temp Errors, Heating Watch, etc.
  1561. TERN_(HAS_HOTEND, manage_hotends(ms));
  1562. #if HAS_TEMP_REDUNDANT
  1563. // Make sure measured temperatures are close together
  1564. if (ABS(degRedundantTarget() - degRedundant()) > TEMP_SENSOR_REDUNDANT_MAX_DIFF)
  1565. _temp_error((heater_id_t)HEATER_ID(TEMP_SENSOR_REDUNDANT_TARGET), F(STR_REDUNDANCY), GET_TEXT_F(MSG_ERR_REDUNDANT_TEMP));
  1566. #endif
  1567. // Manage extruder auto fans and/or read fan tachometers
  1568. TERN_(HAS_FAN_LOGIC, manage_extruder_fans(ms));
  1569. /**
  1570. * Dynamically set the volumetric multiplier based
  1571. * on the delayed Filament Width measurement.
  1572. */
  1573. TERN_(FILAMENT_WIDTH_SENSOR, filwidth.update_volumetric());
  1574. // Handle Bed Temp Errors, Heating Watch, etc.
  1575. TERN_(HAS_HEATED_BED, manage_heated_bed(ms));
  1576. // Handle Heated Chamber Temp Errors, Heating Watch, etc.
  1577. TERN_(HAS_HEATED_CHAMBER, manage_heated_chamber(ms));
  1578. // Handle Cooler Temp Errors, Cooling Watch, etc.
  1579. TERN_(HAS_COOLER, manage_cooler(ms));
  1580. #if ENABLED(LASER_COOLANT_FLOW_METER)
  1581. cooler.flowmeter_task(ms);
  1582. #if ENABLED(FLOWMETER_SAFETY)
  1583. if (cooler.check_flow_too_low()) {
  1584. TERN_(HAS_DISPLAY, if (cutter.enabled()) ui.flow_fault());
  1585. cutter.disable();
  1586. cutter.cutter_mode = CUTTER_MODE_ERROR; // Immediately kill stepper inline power output
  1587. }
  1588. #endif
  1589. #endif
  1590. UNUSED(ms);
  1591. }
  1592. #define TEMP_AD595(RAW) ((RAW) * 5.0 * 100.0 / float(HAL_ADC_RANGE) / (OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET)
  1593. #define TEMP_AD8495(RAW) ((RAW) * 6.6 * 100.0 / float(HAL_ADC_RANGE) / (OVERSAMPLENR) * (TEMP_SENSOR_AD8495_GAIN) + TEMP_SENSOR_AD8495_OFFSET)
  1594. /**
  1595. * Bisect search for the range of the 'raw' value, then interpolate
  1596. * proportionally between the under and over values.
  1597. */
  1598. #define SCAN_THERMISTOR_TABLE(TBL,LEN) do{ \
  1599. uint8_t l = 0, r = LEN, m; \
  1600. for (;;) { \
  1601. m = (l + r) >> 1; \
  1602. if (!m) return celsius_t(pgm_read_word(&TBL[0].celsius)); \
  1603. if (m == l || m == r) return celsius_t(pgm_read_word(&TBL[LEN-1].celsius)); \
  1604. raw_adc_t v00 = pgm_read_word(&TBL[m-1].value), \
  1605. v10 = pgm_read_word(&TBL[m-0].value); \
  1606. if (raw < v00) r = m; \
  1607. else if (raw > v10) l = m; \
  1608. else { \
  1609. const celsius_t v01 = celsius_t(pgm_read_word(&TBL[m-1].celsius)), \
  1610. v11 = celsius_t(pgm_read_word(&TBL[m-0].celsius)); \
  1611. return v01 + (raw - v00) * float(v11 - v01) / float(v10 - v00); \
  1612. } \
  1613. } \
  1614. }while(0)
  1615. #if HAS_USER_THERMISTORS
  1616. user_thermistor_t Temperature::user_thermistor[USER_THERMISTORS]; // Initialized by settings.load()
  1617. void Temperature::reset_user_thermistors() {
  1618. user_thermistor_t default_user_thermistor[USER_THERMISTORS] = {
  1619. #if TEMP_SENSOR_0_IS_CUSTOM
  1620. { true, 0, 0, HOTEND0_PULLUP_RESISTOR_OHMS, HOTEND0_RESISTANCE_25C_OHMS, 0, 0, HOTEND0_BETA, 0 },
  1621. #endif
  1622. #if TEMP_SENSOR_1_IS_CUSTOM
  1623. { true, 0, 0, HOTEND1_PULLUP_RESISTOR_OHMS, HOTEND1_RESISTANCE_25C_OHMS, 0, 0, HOTEND1_BETA, 0 },
  1624. #endif
  1625. #if TEMP_SENSOR_2_IS_CUSTOM
  1626. { true, 0, 0, HOTEND2_PULLUP_RESISTOR_OHMS, HOTEND2_RESISTANCE_25C_OHMS, 0, 0, HOTEND2_BETA, 0 },
  1627. #endif
  1628. #if TEMP_SENSOR_3_IS_CUSTOM
  1629. { true, 0, 0, HOTEND3_PULLUP_RESISTOR_OHMS, HOTEND3_RESISTANCE_25C_OHMS, 0, 0, HOTEND3_BETA, 0 },
  1630. #endif
  1631. #if TEMP_SENSOR_4_IS_CUSTOM
  1632. { true, 0, 0, HOTEND4_PULLUP_RESISTOR_OHMS, HOTEND4_RESISTANCE_25C_OHMS, 0, 0, HOTEND4_BETA, 0 },
  1633. #endif
  1634. #if TEMP_SENSOR_5_IS_CUSTOM
  1635. { true, 0, 0, HOTEND5_PULLUP_RESISTOR_OHMS, HOTEND5_RESISTANCE_25C_OHMS, 0, 0, HOTEND5_BETA, 0 },
  1636. #endif
  1637. #if TEMP_SENSOR_6_IS_CUSTOM
  1638. { true, 0, 0, HOTEND6_PULLUP_RESISTOR_OHMS, HOTEND6_RESISTANCE_25C_OHMS, 0, 0, HOTEND6_BETA, 0 },
  1639. #endif
  1640. #if TEMP_SENSOR_7_IS_CUSTOM
  1641. { true, 0, 0, HOTEND7_PULLUP_RESISTOR_OHMS, HOTEND7_RESISTANCE_25C_OHMS, 0, 0, HOTEND7_BETA, 0 },
  1642. #endif
  1643. #if TEMP_SENSOR_BED_IS_CUSTOM
  1644. { true, 0, 0, BED_PULLUP_RESISTOR_OHMS, BED_RESISTANCE_25C_OHMS, 0, 0, BED_BETA, 0 },
  1645. #endif
  1646. #if TEMP_SENSOR_CHAMBER_IS_CUSTOM
  1647. { true, 0, 0, CHAMBER_PULLUP_RESISTOR_OHMS, CHAMBER_RESISTANCE_25C_OHMS, 0, 0, CHAMBER_BETA, 0 },
  1648. #endif
  1649. #if TEMP_SENSOR_COOLER_IS_CUSTOM
  1650. { true, 0, 0, COOLER_PULLUP_RESISTOR_OHMS, COOLER_RESISTANCE_25C_OHMS, 0, 0, COOLER_BETA, 0 },
  1651. #endif
  1652. #if TEMP_SENSOR_PROBE_IS_CUSTOM
  1653. { true, 0, 0, PROBE_PULLUP_RESISTOR_OHMS, PROBE_RESISTANCE_25C_OHMS, 0, 0, PROBE_BETA, 0 },
  1654. #endif
  1655. #if TEMP_SENSOR_BOARD_IS_CUSTOM
  1656. { true, 0, 0, BOARD_PULLUP_RESISTOR_OHMS, BOARD_RESISTANCE_25C_OHMS, 0, 0, BOARD_BETA, 0 },
  1657. #endif
  1658. #if TEMP_SENSOR_REDUNDANT_IS_CUSTOM
  1659. { true, 0, 0, REDUNDANT_PULLUP_RESISTOR_OHMS, REDUNDANT_RESISTANCE_25C_OHMS, 0, 0, REDUNDANT_BETA, 0 },
  1660. #endif
  1661. };
  1662. COPY(user_thermistor, default_user_thermistor);
  1663. }
  1664. void Temperature::M305_report(const uint8_t t_index, const bool forReplay/*=true*/) {
  1665. gcode.report_heading_etc(forReplay, F(STR_USER_THERMISTORS));
  1666. SERIAL_ECHOPGM(" M305 P", AS_DIGIT(t_index));
  1667. const user_thermistor_t &t = user_thermistor[t_index];
  1668. SERIAL_ECHOPAIR_F(" R", t.series_res, 1);
  1669. SERIAL_ECHOPAIR_F_P(SP_T_STR, t.res_25, 1);
  1670. SERIAL_ECHOPAIR_F_P(SP_B_STR, t.beta, 1);
  1671. SERIAL_ECHOPAIR_F_P(SP_C_STR, t.sh_c_coeff, 9);
  1672. SERIAL_ECHOPGM(" ; ");
  1673. SERIAL_ECHOF(
  1674. TERN_(TEMP_SENSOR_0_IS_CUSTOM, t_index == CTI_HOTEND_0 ? F("HOTEND 0") :)
  1675. TERN_(TEMP_SENSOR_1_IS_CUSTOM, t_index == CTI_HOTEND_1 ? F("HOTEND 1") :)
  1676. TERN_(TEMP_SENSOR_2_IS_CUSTOM, t_index == CTI_HOTEND_2 ? F("HOTEND 2") :)
  1677. TERN_(TEMP_SENSOR_3_IS_CUSTOM, t_index == CTI_HOTEND_3 ? F("HOTEND 3") :)
  1678. TERN_(TEMP_SENSOR_4_IS_CUSTOM, t_index == CTI_HOTEND_4 ? F("HOTEND 4") :)
  1679. TERN_(TEMP_SENSOR_5_IS_CUSTOM, t_index == CTI_HOTEND_5 ? F("HOTEND 5") :)
  1680. TERN_(TEMP_SENSOR_6_IS_CUSTOM, t_index == CTI_HOTEND_6 ? F("HOTEND 6") :)
  1681. TERN_(TEMP_SENSOR_7_IS_CUSTOM, t_index == CTI_HOTEND_7 ? F("HOTEND 7") :)
  1682. TERN_(TEMP_SENSOR_BED_IS_CUSTOM, t_index == CTI_BED ? F("BED") :)
  1683. TERN_(TEMP_SENSOR_CHAMBER_IS_CUSTOM, t_index == CTI_CHAMBER ? F("CHAMBER") :)
  1684. TERN_(TEMP_SENSOR_COOLER_IS_CUSTOM, t_index == CTI_COOLER ? F("COOLER") :)
  1685. TERN_(TEMP_SENSOR_PROBE_IS_CUSTOM, t_index == CTI_PROBE ? F("PROBE") :)
  1686. TERN_(TEMP_SENSOR_BOARD_IS_CUSTOM, t_index == CTI_BOARD ? F("BOARD") :)
  1687. TERN_(TEMP_SENSOR_REDUNDANT_IS_CUSTOM, t_index == CTI_REDUNDANT ? F("REDUNDANT") :)
  1688. nullptr
  1689. );
  1690. SERIAL_EOL();
  1691. }
  1692. celsius_float_t Temperature::user_thermistor_to_deg_c(const uint8_t t_index, const raw_adc_t raw) {
  1693. if (!WITHIN(t_index, 0, COUNT(user_thermistor) - 1)) return 25;
  1694. user_thermistor_t &t = user_thermistor[t_index];
  1695. if (t.pre_calc) { // pre-calculate some variables
  1696. t.pre_calc = false;
  1697. t.res_25_recip = 1.0f / t.res_25;
  1698. t.res_25_log = logf(t.res_25);
  1699. t.beta_recip = 1.0f / t.beta;
  1700. t.sh_alpha = RECIPROCAL(THERMISTOR_RESISTANCE_NOMINAL_C - (THERMISTOR_ABS_ZERO_C))
  1701. - (t.beta_recip * t.res_25_log) - (t.sh_c_coeff * cu(t.res_25_log));
  1702. }
  1703. // Maximum ADC value .. take into account the over sampling
  1704. constexpr raw_adc_t adc_max = MAX_RAW_THERMISTOR_VALUE;
  1705. const raw_adc_t adc_raw = constrain(raw, 1, adc_max - 1); // constrain to prevent divide-by-zero
  1706. const float adc_inverse = (adc_max - adc_raw) - 0.5f,
  1707. resistance = t.series_res * (adc_raw + 0.5f) / adc_inverse,
  1708. log_resistance = logf(resistance);
  1709. float value = t.sh_alpha;
  1710. value += log_resistance * t.beta_recip;
  1711. if (t.sh_c_coeff != 0)
  1712. value += t.sh_c_coeff * cu(log_resistance);
  1713. value = 1.0f / value;
  1714. // Return degrees C (up to 999, as the LCD only displays 3 digits)
  1715. return _MIN(value + THERMISTOR_ABS_ZERO_C, 999);
  1716. }
  1717. #endif
  1718. #if HAS_HOTEND
  1719. // Derived from RepRap FiveD extruder::getTemperature()
  1720. // For hot end temperature measurement.
  1721. celsius_float_t Temperature::analog_to_celsius_hotend(const raw_adc_t raw, const uint8_t e) {
  1722. if (e >= HOTENDS) {
  1723. SERIAL_ERROR_START();
  1724. SERIAL_ECHO(e);
  1725. SERIAL_ECHOLNPGM(STR_INVALID_EXTRUDER_NUM);
  1726. kill();
  1727. return 0;
  1728. }
  1729. switch (e) {
  1730. case 0:
  1731. #if TEMP_SENSOR_0_IS_CUSTOM
  1732. return user_thermistor_to_deg_c(CTI_HOTEND_0, raw);
  1733. #elif TEMP_SENSOR_0_IS_MAX_TC
  1734. #if TEMP_SENSOR_0_IS_MAX31865
  1735. return TERN(LIB_INTERNAL_MAX31865,
  1736. max31865_0.temperature(raw),
  1737. max31865_0.temperature(MAX31865_SENSOR_OHMS_0, MAX31865_CALIBRATION_OHMS_0)
  1738. );
  1739. #else
  1740. return (int16_t)raw * 0.25;
  1741. #endif
  1742. #elif TEMP_SENSOR_0_IS_AD595
  1743. return TEMP_AD595(raw);
  1744. #elif TEMP_SENSOR_0_IS_AD8495
  1745. return TEMP_AD8495(raw);
  1746. #else
  1747. break;
  1748. #endif
  1749. case 1:
  1750. #if TEMP_SENSOR_1_IS_CUSTOM
  1751. return user_thermistor_to_deg_c(CTI_HOTEND_1, raw);
  1752. #elif TEMP_SENSOR_1_IS_MAX_TC
  1753. #if TEMP_SENSOR_0_IS_MAX31865
  1754. return TERN(LIB_INTERNAL_MAX31865,
  1755. max31865_1.temperature(raw),
  1756. max31865_1.temperature(MAX31865_SENSOR_OHMS_1, MAX31865_CALIBRATION_OHMS_1)
  1757. );
  1758. #else
  1759. return (int16_t)raw * 0.25;
  1760. #endif
  1761. #elif TEMP_SENSOR_1_IS_AD595
  1762. return TEMP_AD595(raw);
  1763. #elif TEMP_SENSOR_1_IS_AD8495
  1764. return TEMP_AD8495(raw);
  1765. #else
  1766. break;
  1767. #endif
  1768. case 2:
  1769. #if TEMP_SENSOR_2_IS_CUSTOM
  1770. return user_thermistor_to_deg_c(CTI_HOTEND_2, raw);
  1771. #elif TEMP_SENSOR_2_IS_AD595
  1772. return TEMP_AD595(raw);
  1773. #elif TEMP_SENSOR_2_IS_AD8495
  1774. return TEMP_AD8495(raw);
  1775. #else
  1776. break;
  1777. #endif
  1778. case 3:
  1779. #if TEMP_SENSOR_3_IS_CUSTOM
  1780. return user_thermistor_to_deg_c(CTI_HOTEND_3, raw);
  1781. #elif TEMP_SENSOR_3_IS_AD595
  1782. return TEMP_AD595(raw);
  1783. #elif TEMP_SENSOR_3_IS_AD8495
  1784. return TEMP_AD8495(raw);
  1785. #else
  1786. break;
  1787. #endif
  1788. case 4:
  1789. #if TEMP_SENSOR_4_IS_CUSTOM
  1790. return user_thermistor_to_deg_c(CTI_HOTEND_4, raw);
  1791. #elif TEMP_SENSOR_4_IS_AD595
  1792. return TEMP_AD595(raw);
  1793. #elif TEMP_SENSOR_4_IS_AD8495
  1794. return TEMP_AD8495(raw);
  1795. #else
  1796. break;
  1797. #endif
  1798. case 5:
  1799. #if TEMP_SENSOR_5_IS_CUSTOM
  1800. return user_thermistor_to_deg_c(CTI_HOTEND_5, raw);
  1801. #elif TEMP_SENSOR_5_IS_AD595
  1802. return TEMP_AD595(raw);
  1803. #elif TEMP_SENSOR_5_IS_AD8495
  1804. return TEMP_AD8495(raw);
  1805. #else
  1806. break;
  1807. #endif
  1808. case 6:
  1809. #if TEMP_SENSOR_6_IS_CUSTOM
  1810. return user_thermistor_to_deg_c(CTI_HOTEND_6, raw);
  1811. #elif TEMP_SENSOR_6_IS_AD595
  1812. return TEMP_AD595(raw);
  1813. #elif TEMP_SENSOR_6_IS_AD8495
  1814. return TEMP_AD8495(raw);
  1815. #else
  1816. break;
  1817. #endif
  1818. case 7:
  1819. #if TEMP_SENSOR_7_IS_CUSTOM
  1820. return user_thermistor_to_deg_c(CTI_HOTEND_7, raw);
  1821. #elif TEMP_SENSOR_7_IS_AD595
  1822. return TEMP_AD595(raw);
  1823. #elif TEMP_SENSOR_7_IS_AD8495
  1824. return TEMP_AD8495(raw);
  1825. #else
  1826. break;
  1827. #endif
  1828. default: break;
  1829. }
  1830. #if HAS_HOTEND_THERMISTOR
  1831. // Thermistor with conversion table?
  1832. const temp_entry_t(*tt)[] = (temp_entry_t(*)[])(heater_ttbl_map[e]);
  1833. SCAN_THERMISTOR_TABLE((*tt), heater_ttbllen_map[e]);
  1834. #endif
  1835. return 0;
  1836. }
  1837. #endif // HAS_HOTEND
  1838. #if HAS_HEATED_BED
  1839. // For bed temperature measurement.
  1840. celsius_float_t Temperature::analog_to_celsius_bed(const raw_adc_t raw) {
  1841. #if TEMP_SENSOR_BED_IS_CUSTOM
  1842. return user_thermistor_to_deg_c(CTI_BED, raw);
  1843. #elif TEMP_SENSOR_BED_IS_THERMISTOR
  1844. SCAN_THERMISTOR_TABLE(TEMPTABLE_BED, TEMPTABLE_BED_LEN);
  1845. #elif TEMP_SENSOR_BED_IS_AD595
  1846. return TEMP_AD595(raw);
  1847. #elif TEMP_SENSOR_BED_IS_AD8495
  1848. return TEMP_AD8495(raw);
  1849. #else
  1850. UNUSED(raw);
  1851. return 0;
  1852. #endif
  1853. }
  1854. #endif // HAS_HEATED_BED
  1855. #if HAS_TEMP_CHAMBER
  1856. // For chamber temperature measurement.
  1857. celsius_float_t Temperature::analog_to_celsius_chamber(const raw_adc_t raw) {
  1858. #if TEMP_SENSOR_CHAMBER_IS_CUSTOM
  1859. return user_thermistor_to_deg_c(CTI_CHAMBER, raw);
  1860. #elif TEMP_SENSOR_CHAMBER_IS_THERMISTOR
  1861. SCAN_THERMISTOR_TABLE(TEMPTABLE_CHAMBER, TEMPTABLE_CHAMBER_LEN);
  1862. #elif TEMP_SENSOR_CHAMBER_IS_AD595
  1863. return TEMP_AD595(raw);
  1864. #elif TEMP_SENSOR_CHAMBER_IS_AD8495
  1865. return TEMP_AD8495(raw);
  1866. #else
  1867. UNUSED(raw);
  1868. return 0;
  1869. #endif
  1870. }
  1871. #endif // HAS_TEMP_CHAMBER
  1872. #if HAS_TEMP_COOLER
  1873. // For cooler temperature measurement.
  1874. celsius_float_t Temperature::analog_to_celsius_cooler(const raw_adc_t raw) {
  1875. #if TEMP_SENSOR_COOLER_IS_CUSTOM
  1876. return user_thermistor_to_deg_c(CTI_COOLER, raw);
  1877. #elif TEMP_SENSOR_COOLER_IS_THERMISTOR
  1878. SCAN_THERMISTOR_TABLE(TEMPTABLE_COOLER, TEMPTABLE_COOLER_LEN);
  1879. #elif TEMP_SENSOR_COOLER_IS_AD595
  1880. return TEMP_AD595(raw);
  1881. #elif TEMP_SENSOR_COOLER_IS_AD8495
  1882. return TEMP_AD8495(raw);
  1883. #else
  1884. UNUSED(raw);
  1885. return 0;
  1886. #endif
  1887. }
  1888. #endif // HAS_TEMP_COOLER
  1889. #if HAS_TEMP_PROBE
  1890. // For probe temperature measurement.
  1891. celsius_float_t Temperature::analog_to_celsius_probe(const raw_adc_t raw) {
  1892. #if TEMP_SENSOR_PROBE_IS_CUSTOM
  1893. return user_thermistor_to_deg_c(CTI_PROBE, raw);
  1894. #elif TEMP_SENSOR_PROBE_IS_THERMISTOR
  1895. SCAN_THERMISTOR_TABLE(TEMPTABLE_PROBE, TEMPTABLE_PROBE_LEN);
  1896. #elif TEMP_SENSOR_PROBE_IS_AD595
  1897. return TEMP_AD595(raw);
  1898. #elif TEMP_SENSOR_PROBE_IS_AD8495
  1899. return TEMP_AD8495(raw);
  1900. #else
  1901. UNUSED(raw);
  1902. return 0;
  1903. #endif
  1904. }
  1905. #endif // HAS_TEMP_PROBE
  1906. #if HAS_TEMP_BOARD
  1907. // For motherboard temperature measurement.
  1908. celsius_float_t Temperature::analog_to_celsius_board(const raw_adc_t raw) {
  1909. #if TEMP_SENSOR_BOARD_IS_CUSTOM
  1910. return user_thermistor_to_deg_c(CTI_BOARD, raw);
  1911. #elif TEMP_SENSOR_BOARD_IS_THERMISTOR
  1912. SCAN_THERMISTOR_TABLE(TEMPTABLE_BOARD, TEMPTABLE_BOARD_LEN);
  1913. #elif TEMP_SENSOR_BOARD_IS_AD595
  1914. return TEMP_AD595(raw);
  1915. #elif TEMP_SENSOR_BOARD_IS_AD8495
  1916. return TEMP_AD8495(raw);
  1917. #else
  1918. UNUSED(raw);
  1919. return 0;
  1920. #endif
  1921. }
  1922. #endif // HAS_TEMP_BOARD
  1923. #if HAS_TEMP_REDUNDANT
  1924. // For redundant temperature measurement.
  1925. celsius_float_t Temperature::analog_to_celsius_redundant(const raw_adc_t raw) {
  1926. #if TEMP_SENSOR_REDUNDANT_IS_CUSTOM
  1927. return user_thermistor_to_deg_c(CTI_REDUNDANT, raw);
  1928. #elif TEMP_SENSOR_REDUNDANT_IS_MAX_TC && REDUNDANT_TEMP_MATCH(SOURCE, E0)
  1929. return TERN(TEMP_SENSOR_REDUNDANT_IS_MAX31865, max31865_0.temperature(raw), (int16_t)raw * 0.25);
  1930. #elif TEMP_SENSOR_REDUNDANT_IS_MAX_TC && REDUNDANT_TEMP_MATCH(SOURCE, E1)
  1931. return TERN(TEMP_SENSOR_REDUNDANT_IS_MAX31865, max31865_1.temperature(raw), (int16_t)raw * 0.25);
  1932. #elif TEMP_SENSOR_REDUNDANT_IS_THERMISTOR
  1933. SCAN_THERMISTOR_TABLE(TEMPTABLE_REDUNDANT, TEMPTABLE_REDUNDANT_LEN);
  1934. #elif TEMP_SENSOR_REDUNDANT_IS_AD595
  1935. return TEMP_AD595(raw);
  1936. #elif TEMP_SENSOR_REDUNDANT_IS_AD8495
  1937. return TEMP_AD8495(raw);
  1938. #else
  1939. UNUSED(raw);
  1940. return 0;
  1941. #endif
  1942. }
  1943. #endif // HAS_TEMP_REDUNDANT
  1944. /**
  1945. * Convert the raw sensor readings into actual Celsius temperatures and
  1946. * validate raw temperatures. Bad readings generate min/maxtemp errors.
  1947. *
  1948. * The raw values are generated entirely in interrupt context, and this
  1949. * method is called from normal context once 'raw_temps_ready' has been
  1950. * set by update_raw_temperatures().
  1951. *
  1952. * The watchdog is dependent on this method. If 'raw_temps_ready' stops
  1953. * being set by the interrupt so that this method is not called for over
  1954. * 4 seconds then something has gone afoul and the machine will be reset.
  1955. */
  1956. void Temperature::updateTemperaturesFromRawValues() {
  1957. hal.watchdog_refresh(); // Reset because raw_temps_ready was set by the interrupt
  1958. TERN_(TEMP_SENSOR_0_IS_MAX_TC, temp_hotend[0].setraw(READ_MAX_TC(0)));
  1959. TERN_(TEMP_SENSOR_1_IS_MAX_TC, temp_hotend[1].setraw(READ_MAX_TC(1)));
  1960. TERN_(TEMP_SENSOR_REDUNDANT_IS_MAX_TC, temp_redundant.setraw(READ_MAX_TC(HEATER_ID(TEMP_SENSOR_REDUNDANT_SOURCE))));
  1961. #if HAS_HOTEND
  1962. HOTEND_LOOP() temp_hotend[e].celsius = analog_to_celsius_hotend(temp_hotend[e].getraw(), e);
  1963. #endif
  1964. TERN_(HAS_HEATED_BED, temp_bed.celsius = analog_to_celsius_bed(temp_bed.getraw()));
  1965. TERN_(HAS_TEMP_CHAMBER, temp_chamber.celsius = analog_to_celsius_chamber(temp_chamber.getraw()));
  1966. TERN_(HAS_TEMP_COOLER, temp_cooler.celsius = analog_to_celsius_cooler(temp_cooler.getraw()));
  1967. TERN_(HAS_TEMP_PROBE, temp_probe.celsius = analog_to_celsius_probe(temp_probe.getraw()));
  1968. TERN_(HAS_TEMP_BOARD, temp_board.celsius = analog_to_celsius_board(temp_board.getraw()));
  1969. TERN_(HAS_TEMP_REDUNDANT, temp_redundant.celsius = analog_to_celsius_redundant(temp_redundant.getraw()));
  1970. TERN_(FILAMENT_WIDTH_SENSOR, filwidth.update_measured_mm());
  1971. TERN_(HAS_POWER_MONITOR, power_monitor.capture_values());
  1972. #if HAS_HOTEND
  1973. static constexpr int8_t temp_dir[] = {
  1974. #if TEMP_SENSOR_IS_ANY_MAX_TC(0)
  1975. 0
  1976. #else
  1977. TEMPDIR(0)
  1978. #endif
  1979. #if HAS_MULTI_HOTEND
  1980. #if TEMP_SENSOR_IS_ANY_MAX_TC(1)
  1981. , 0
  1982. #else
  1983. , TEMPDIR(1)
  1984. #endif
  1985. #if HOTENDS > 2
  1986. #define _TEMPDIR(N) , TEMPDIR(N)
  1987. REPEAT_S(2, HOTENDS, _TEMPDIR)
  1988. #endif
  1989. #endif
  1990. };
  1991. LOOP_L_N(e, COUNT(temp_dir)) {
  1992. const raw_adc_t r = temp_hotend[e].getraw();
  1993. const bool neg = temp_dir[e] < 0, pos = temp_dir[e] > 0;
  1994. if ((neg && r < temp_range[e].raw_max) || (pos && r > temp_range[e].raw_max))
  1995. max_temp_error((heater_id_t)e);
  1996. const bool heater_on = temp_hotend[e].target > 0;
  1997. if (heater_on && ((neg && r > temp_range[e].raw_min) || (pos && r < temp_range[e].raw_min))) {
  1998. #if MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED > 1
  1999. if (++consecutive_low_temperature_error[e] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
  2000. #endif
  2001. min_temp_error((heater_id_t)e);
  2002. }
  2003. #if MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED > 1
  2004. else
  2005. consecutive_low_temperature_error[e] = 0;
  2006. #endif
  2007. }
  2008. #endif // HAS_HOTEND
  2009. #define TP_CMP(S,A,B) (TEMPDIR(S) < 0 ? ((A)<(B)) : ((A)>(B)))
  2010. #if ENABLED(THERMAL_PROTECTION_BED)
  2011. if (TP_CMP(BED, temp_bed.getraw(), maxtemp_raw_BED)) max_temp_error(H_BED);
  2012. if (temp_bed.target > 0 && TP_CMP(BED, mintemp_raw_BED, temp_bed.getraw())) min_temp_error(H_BED);
  2013. #endif
  2014. #if BOTH(HAS_HEATED_CHAMBER, THERMAL_PROTECTION_CHAMBER)
  2015. if (TP_CMP(CHAMBER, temp_chamber.getraw(), maxtemp_raw_CHAMBER)) max_temp_error(H_CHAMBER);
  2016. if (temp_chamber.target > 0 && TP_CMP(CHAMBER, mintemp_raw_CHAMBER, temp_chamber.getraw())) min_temp_error(H_CHAMBER);
  2017. #endif
  2018. #if BOTH(HAS_COOLER, THERMAL_PROTECTION_COOLER)
  2019. if (cutter.unitPower > 0 && TP_CMP(COOLER, temp_cooler.getraw(), maxtemp_raw_COOLER)) max_temp_error(H_COOLER);
  2020. if (TP_CMP(COOLER, mintemp_raw_COOLER, temp_cooler.getraw())) min_temp_error(H_COOLER);
  2021. #endif
  2022. #if BOTH(HAS_TEMP_BOARD, THERMAL_PROTECTION_BOARD)
  2023. if (TP_CMP(BOARD, temp_board.getraw(), maxtemp_raw_BOARD)) max_temp_error(H_BOARD);
  2024. if (TP_CMP(BOARD, mintemp_raw_BOARD, temp_board.getraw())) min_temp_error(H_BOARD);
  2025. #endif
  2026. #undef TP_CMP
  2027. } // Temperature::updateTemperaturesFromRawValues
  2028. /**
  2029. * Initialize the temperature manager
  2030. *
  2031. * The manager is implemented by periodic calls to task()
  2032. *
  2033. * - Init (and disable) SPI thermocouples like MAX6675 and MAX31865
  2034. * - Disable RUMBA JTAG to accommodate a thermocouple extension
  2035. * - Read-enable thermistors with a read-enable pin
  2036. * - Init HEATER and COOLER pins for OUTPUT in OFF state
  2037. * - Init the FAN pins as PWM or OUTPUT
  2038. * - Init the SPI interface for SPI thermocouples
  2039. * - Init ADC according to the HAL
  2040. * - Set thermistor pins to analog inputs according to the HAL
  2041. * - Start the Temperature ISR timer
  2042. * - Init the AUTO FAN pins as PWM or OUTPUT
  2043. * - Wait 250ms for temperatures to settle
  2044. * - Init temp_range[], used for catching min/maxtemp
  2045. */
  2046. void Temperature::init() {
  2047. TERN_(PROBING_HEATERS_OFF, paused_for_probing = false);
  2048. #if BOTH(PIDTEMP, PID_EXTRUSION_SCALING)
  2049. pes_e_position = 0;
  2050. #endif
  2051. // Init (and disable) SPI thermocouples
  2052. #if TEMP_SENSOR_IS_ANY_MAX_TC(0) && PIN_EXISTS(TEMP_0_CS)
  2053. OUT_WRITE(TEMP_0_CS_PIN, HIGH);
  2054. #endif
  2055. #if TEMP_SENSOR_IS_ANY_MAX_TC(1) && PIN_EXISTS(TEMP_1_CS)
  2056. OUT_WRITE(TEMP_1_CS_PIN, HIGH);
  2057. #endif
  2058. // Setup objects for library-based polling of MAX TCs
  2059. #if HAS_MAXTC_LIBRARIES
  2060. #define _MAX31865_WIRES(n) MAX31865_##n##WIRE
  2061. #define MAX31865_WIRES(n) _MAX31865_WIRES(n)
  2062. #if TEMP_SENSOR_IS_MAX(0, 6675) && HAS_MAX6675_LIBRARY
  2063. max6675_0.begin();
  2064. #elif TEMP_SENSOR_IS_MAX(0, 31855) && HAS_MAX31855_LIBRARY
  2065. max31855_0.begin();
  2066. #elif TEMP_SENSOR_IS_MAX(0, 31865)
  2067. max31865_0.begin(
  2068. MAX31865_WIRES(MAX31865_SENSOR_WIRES_0) // MAX31865_2WIRE, MAX31865_3WIRE, MAX31865_4WIRE
  2069. OPTARG(LIB_INTERNAL_MAX31865, MAX31865_SENSOR_OHMS_0, MAX31865_CALIBRATION_OHMS_0, MAX31865_WIRE_OHMS_0)
  2070. );
  2071. #endif
  2072. #if TEMP_SENSOR_IS_MAX(1, 6675) && HAS_MAX6675_LIBRARY
  2073. max6675_1.begin();
  2074. #elif TEMP_SENSOR_IS_MAX(1, 31855) && HAS_MAX31855_LIBRARY
  2075. max31855_1.begin();
  2076. #elif TEMP_SENSOR_IS_MAX(1, 31865)
  2077. max31865_1.begin(
  2078. MAX31865_WIRES(MAX31865_SENSOR_WIRES_1) // MAX31865_2WIRE, MAX31865_3WIRE, MAX31865_4WIRE
  2079. OPTARG(LIB_INTERNAL_MAX31865, MAX31865_SENSOR_OHMS_1, MAX31865_CALIBRATION_OHMS_1, MAX31865_WIRE_OHMS_1)
  2080. );
  2081. #endif
  2082. #undef MAX31865_WIRES
  2083. #undef _MAX31865_WIRES
  2084. #endif
  2085. #if MB(RUMBA)
  2086. // Disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
  2087. #define _AD(N) (TEMP_SENSOR_##N##_IS_AD595 || TEMP_SENSOR_##N##_IS_AD8495)
  2088. #if _AD(0) || _AD(1) || _AD(2) || _AD(BED) || _AD(CHAMBER) || _AD(REDUNDANT)
  2089. MCUCR = _BV(JTD);
  2090. MCUCR = _BV(JTD);
  2091. #endif
  2092. #endif
  2093. // Thermistor activation by MCU pin
  2094. #if PIN_EXISTS(TEMP_0_TR_ENABLE)
  2095. OUT_WRITE(TEMP_0_TR_ENABLE_PIN, (
  2096. #if TEMP_SENSOR_IS_ANY_MAX_TC(0)
  2097. HIGH
  2098. #else
  2099. LOW
  2100. #endif
  2101. ));
  2102. #endif
  2103. #if PIN_EXISTS(TEMP_1_TR_ENABLE)
  2104. OUT_WRITE(TEMP_1_TR_ENABLE_PIN, (
  2105. #if TEMP_SENSOR_IS_ANY_MAX_TC(1)
  2106. HIGH
  2107. #else
  2108. LOW
  2109. #endif
  2110. ));
  2111. #endif
  2112. #if ENABLED(MPCTEMP)
  2113. HOTEND_LOOP() temp_hotend[e].modeled_block_temp = NAN;
  2114. #endif
  2115. #if HAS_HEATER_0
  2116. #ifdef BOARD_OPENDRAIN_MOSFETS
  2117. OUT_WRITE_OD(HEATER_0_PIN, HEATER_0_INVERTING);
  2118. #else
  2119. OUT_WRITE(HEATER_0_PIN, HEATER_0_INVERTING);
  2120. #endif
  2121. #endif
  2122. #if HAS_HEATER_1
  2123. OUT_WRITE(HEATER_1_PIN, HEATER_1_INVERTING);
  2124. #endif
  2125. #if HAS_HEATER_2
  2126. OUT_WRITE(HEATER_2_PIN, HEATER_2_INVERTING);
  2127. #endif
  2128. #if HAS_HEATER_3
  2129. OUT_WRITE(HEATER_3_PIN, HEATER_3_INVERTING);
  2130. #endif
  2131. #if HAS_HEATER_4
  2132. OUT_WRITE(HEATER_4_PIN, HEATER_4_INVERTING);
  2133. #endif
  2134. #if HAS_HEATER_5
  2135. OUT_WRITE(HEATER_5_PIN, HEATER_5_INVERTING);
  2136. #endif
  2137. #if HAS_HEATER_6
  2138. OUT_WRITE(HEATER_6_PIN, HEATER_6_INVERTING);
  2139. #endif
  2140. #if HAS_HEATER_7
  2141. OUT_WRITE(HEATER_7_PIN, HEATER_7_INVERTING);
  2142. #endif
  2143. #if HAS_HEATED_BED
  2144. #ifdef BOARD_OPENDRAIN_MOSFETS
  2145. OUT_WRITE_OD(HEATER_BED_PIN, HEATER_BED_INVERTING);
  2146. #else
  2147. OUT_WRITE(HEATER_BED_PIN, HEATER_BED_INVERTING);
  2148. #endif
  2149. #endif
  2150. #if HAS_HEATED_CHAMBER
  2151. OUT_WRITE(HEATER_CHAMBER_PIN, HEATER_CHAMBER_INVERTING);
  2152. #endif
  2153. #if HAS_COOLER
  2154. OUT_WRITE(COOLER_PIN, COOLER_INVERTING);
  2155. #endif
  2156. #if HAS_FAN0
  2157. INIT_FAN_PIN(FAN_PIN);
  2158. #endif
  2159. #if HAS_FAN1
  2160. INIT_FAN_PIN(FAN1_PIN);
  2161. #endif
  2162. #if HAS_FAN2
  2163. INIT_FAN_PIN(FAN2_PIN);
  2164. #endif
  2165. #if HAS_FAN3
  2166. INIT_FAN_PIN(FAN3_PIN);
  2167. #endif
  2168. #if HAS_FAN4
  2169. INIT_FAN_PIN(FAN4_PIN);
  2170. #endif
  2171. #if HAS_FAN5
  2172. INIT_FAN_PIN(FAN5_PIN);
  2173. #endif
  2174. #if HAS_FAN6
  2175. INIT_FAN_PIN(FAN6_PIN);
  2176. #endif
  2177. #if HAS_FAN7
  2178. INIT_FAN_PIN(FAN7_PIN);
  2179. #endif
  2180. #if ENABLED(USE_CONTROLLER_FAN)
  2181. INIT_FAN_PIN(CONTROLLER_FAN_PIN);
  2182. #endif
  2183. TERN_(HAS_MAXTC_SW_SPI, max_tc_spi.init());
  2184. hal.adc_init();
  2185. TERN_(HAS_TEMP_ADC_0, hal.adc_enable(TEMP_0_PIN));
  2186. TERN_(HAS_TEMP_ADC_1, hal.adc_enable(TEMP_1_PIN));
  2187. TERN_(HAS_TEMP_ADC_2, hal.adc_enable(TEMP_2_PIN));
  2188. TERN_(HAS_TEMP_ADC_3, hal.adc_enable(TEMP_3_PIN));
  2189. TERN_(HAS_TEMP_ADC_4, hal.adc_enable(TEMP_4_PIN));
  2190. TERN_(HAS_TEMP_ADC_5, hal.adc_enable(TEMP_5_PIN));
  2191. TERN_(HAS_TEMP_ADC_6, hal.adc_enable(TEMP_6_PIN));
  2192. TERN_(HAS_TEMP_ADC_7, hal.adc_enable(TEMP_7_PIN));
  2193. TERN_(HAS_JOY_ADC_X, hal.adc_enable(JOY_X_PIN));
  2194. TERN_(HAS_JOY_ADC_Y, hal.adc_enable(JOY_Y_PIN));
  2195. TERN_(HAS_JOY_ADC_Z, hal.adc_enable(JOY_Z_PIN));
  2196. TERN_(HAS_TEMP_ADC_BED, hal.adc_enable(TEMP_BED_PIN));
  2197. TERN_(HAS_TEMP_ADC_CHAMBER, hal.adc_enable(TEMP_CHAMBER_PIN));
  2198. TERN_(HAS_TEMP_ADC_PROBE, hal.adc_enable(TEMP_PROBE_PIN));
  2199. TERN_(HAS_TEMP_ADC_COOLER, hal.adc_enable(TEMP_COOLER_PIN));
  2200. TERN_(HAS_TEMP_ADC_BOARD, hal.adc_enable(TEMP_BOARD_PIN));
  2201. TERN_(HAS_TEMP_ADC_REDUNDANT, hal.adc_enable(TEMP_REDUNDANT_PIN));
  2202. TERN_(FILAMENT_WIDTH_SENSOR, hal.adc_enable(FILWIDTH_PIN));
  2203. TERN_(HAS_ADC_BUTTONS, hal.adc_enable(ADC_KEYPAD_PIN));
  2204. TERN_(POWER_MONITOR_CURRENT, hal.adc_enable(POWER_MONITOR_CURRENT_PIN));
  2205. TERN_(POWER_MONITOR_VOLTAGE, hal.adc_enable(POWER_MONITOR_VOLTAGE_PIN));
  2206. #if HAS_JOY_ADC_EN
  2207. SET_INPUT_PULLUP(JOY_EN_PIN);
  2208. #endif
  2209. HAL_timer_start(MF_TIMER_TEMP, TEMP_TIMER_FREQUENCY);
  2210. ENABLE_TEMPERATURE_INTERRUPT();
  2211. #if HAS_AUTO_FAN_0
  2212. INIT_E_AUTO_FAN_PIN(E0_AUTO_FAN_PIN);
  2213. #endif
  2214. #if HAS_AUTO_FAN_1 && !_EFANOVERLAP(1,0)
  2215. INIT_E_AUTO_FAN_PIN(E1_AUTO_FAN_PIN);
  2216. #endif
  2217. #if HAS_AUTO_FAN_2 && !(_EFANOVERLAP(2,0) || _EFANOVERLAP(2,1))
  2218. INIT_E_AUTO_FAN_PIN(E2_AUTO_FAN_PIN);
  2219. #endif
  2220. #if HAS_AUTO_FAN_3 && !(_EFANOVERLAP(3,0) || _EFANOVERLAP(3,1) || _EFANOVERLAP(3,2))
  2221. INIT_E_AUTO_FAN_PIN(E3_AUTO_FAN_PIN);
  2222. #endif
  2223. #if HAS_AUTO_FAN_4 && !(_EFANOVERLAP(4,0) || _EFANOVERLAP(4,1) || _EFANOVERLAP(4,2) || _EFANOVERLAP(4,3))
  2224. INIT_E_AUTO_FAN_PIN(E4_AUTO_FAN_PIN);
  2225. #endif
  2226. #if HAS_AUTO_FAN_5 && !(_EFANOVERLAP(5,0) || _EFANOVERLAP(5,1) || _EFANOVERLAP(5,2) || _EFANOVERLAP(5,3) || _EFANOVERLAP(5,4))
  2227. INIT_E_AUTO_FAN_PIN(E5_AUTO_FAN_PIN);
  2228. #endif
  2229. #if HAS_AUTO_FAN_6 && !(_EFANOVERLAP(6,0) || _EFANOVERLAP(6,1) || _EFANOVERLAP(6,2) || _EFANOVERLAP(6,3) || _EFANOVERLAP(6,4) || _EFANOVERLAP(6,5))
  2230. INIT_E_AUTO_FAN_PIN(E6_AUTO_FAN_PIN);
  2231. #endif
  2232. #if HAS_AUTO_FAN_7 && !(_EFANOVERLAP(7,0) || _EFANOVERLAP(7,1) || _EFANOVERLAP(7,2) || _EFANOVERLAP(7,3) || _EFANOVERLAP(7,4) || _EFANOVERLAP(7,5) || _EFANOVERLAP(7,6))
  2233. INIT_E_AUTO_FAN_PIN(E7_AUTO_FAN_PIN);
  2234. #endif
  2235. #if HAS_AUTO_CHAMBER_FAN && !AUTO_CHAMBER_IS_E
  2236. INIT_CHAMBER_AUTO_FAN_PIN(CHAMBER_AUTO_FAN_PIN);
  2237. #endif
  2238. #if HAS_HOTEND
  2239. #define _TEMP_MIN_E(NR) do{ \
  2240. const celsius_t tmin_tmp = TERN(TEMP_SENSOR_##NR##_IS_CUSTOM, 0, int16_t(pgm_read_word(&TEMPTABLE_##NR [TEMP_SENSOR_##NR##_MINTEMP_IND].celsius))), \
  2241. tmin = _MAX(HEATER_##NR##_MINTEMP, tmin_tmp); \
  2242. temp_range[NR].mintemp = tmin; \
  2243. while (analog_to_celsius_hotend(temp_range[NR].raw_min, NR) < tmin) \
  2244. temp_range[NR].raw_min += TEMPDIR(NR) * (OVERSAMPLENR); \
  2245. }while(0)
  2246. #define _TEMP_MAX_E(NR) do{ \
  2247. const celsius_t tmax_tmp = TERN(TEMP_SENSOR_##NR##_IS_CUSTOM, 2000, int16_t(pgm_read_word(&TEMPTABLE_##NR [TEMP_SENSOR_##NR##_MAXTEMP_IND].celsius)) - 1), \
  2248. tmax = _MIN(HEATER_##NR##_MAXTEMP, tmax_tmp); \
  2249. temp_range[NR].maxtemp = tmax; \
  2250. while (analog_to_celsius_hotend(temp_range[NR].raw_max, NR) > tmax) \
  2251. temp_range[NR].raw_max -= TEMPDIR(NR) * (OVERSAMPLENR); \
  2252. }while(0)
  2253. #define _MINMAX_TEST(N,M) (HOTENDS > N && TEMP_SENSOR_##N > 0 && TEMP_SENSOR_##N != 998 && TEMP_SENSOR_##N != 999 && defined(HEATER_##N##_##M##TEMP))
  2254. #if _MINMAX_TEST(0, MIN)
  2255. _TEMP_MIN_E(0);
  2256. #endif
  2257. #if _MINMAX_TEST(0, MAX)
  2258. _TEMP_MAX_E(0);
  2259. #endif
  2260. #if _MINMAX_TEST(1, MIN)
  2261. _TEMP_MIN_E(1);
  2262. #endif
  2263. #if _MINMAX_TEST(1, MAX)
  2264. _TEMP_MAX_E(1);
  2265. #endif
  2266. #if _MINMAX_TEST(2, MIN)
  2267. _TEMP_MIN_E(2);
  2268. #endif
  2269. #if _MINMAX_TEST(2, MAX)
  2270. _TEMP_MAX_E(2);
  2271. #endif
  2272. #if _MINMAX_TEST(3, MIN)
  2273. _TEMP_MIN_E(3);
  2274. #endif
  2275. #if _MINMAX_TEST(3, MAX)
  2276. _TEMP_MAX_E(3);
  2277. #endif
  2278. #if _MINMAX_TEST(4, MIN)
  2279. _TEMP_MIN_E(4);
  2280. #endif
  2281. #if _MINMAX_TEST(4, MAX)
  2282. _TEMP_MAX_E(4);
  2283. #endif
  2284. #if _MINMAX_TEST(5, MIN)
  2285. _TEMP_MIN_E(5);
  2286. #endif
  2287. #if _MINMAX_TEST(5, MAX)
  2288. _TEMP_MAX_E(5);
  2289. #endif
  2290. #if _MINMAX_TEST(6, MIN)
  2291. _TEMP_MIN_E(6);
  2292. #endif
  2293. #if _MINMAX_TEST(6, MAX)
  2294. _TEMP_MAX_E(6);
  2295. #endif
  2296. #if _MINMAX_TEST(7, MIN)
  2297. _TEMP_MIN_E(7);
  2298. #endif
  2299. #if _MINMAX_TEST(7, MAX)
  2300. _TEMP_MAX_E(7);
  2301. #endif
  2302. #endif // HAS_HOTEND
  2303. // TODO: combine these into the macros above
  2304. #if HAS_HEATED_BED
  2305. while (analog_to_celsius_bed(mintemp_raw_BED) < BED_MINTEMP) mintemp_raw_BED += TEMPDIR(BED) * (OVERSAMPLENR);
  2306. while (analog_to_celsius_bed(maxtemp_raw_BED) > BED_MAXTEMP) maxtemp_raw_BED -= TEMPDIR(BED) * (OVERSAMPLENR);
  2307. #endif
  2308. #if HAS_HEATED_CHAMBER
  2309. while (analog_to_celsius_chamber(mintemp_raw_CHAMBER) < CHAMBER_MINTEMP) mintemp_raw_CHAMBER += TEMPDIR(CHAMBER) * (OVERSAMPLENR);
  2310. while (analog_to_celsius_chamber(maxtemp_raw_CHAMBER) > CHAMBER_MAXTEMP) maxtemp_raw_CHAMBER -= TEMPDIR(CHAMBER) * (OVERSAMPLENR);
  2311. #endif
  2312. #if HAS_COOLER
  2313. while (analog_to_celsius_cooler(mintemp_raw_COOLER) > COOLER_MINTEMP) mintemp_raw_COOLER += TEMPDIR(COOLER) * (OVERSAMPLENR);
  2314. while (analog_to_celsius_cooler(maxtemp_raw_COOLER) < COOLER_MAXTEMP) maxtemp_raw_COOLER -= TEMPDIR(COOLER) * (OVERSAMPLENR);
  2315. #endif
  2316. #if BOTH(HAS_TEMP_BOARD, THERMAL_PROTECTION_BOARD)
  2317. while (analog_to_celsius_board(mintemp_raw_BOARD) < BOARD_MINTEMP) mintemp_raw_BOARD += TEMPDIR(BOARD) * (OVERSAMPLENR);
  2318. while (analog_to_celsius_board(maxtemp_raw_BOARD) > BOARD_MAXTEMP) maxtemp_raw_BOARD -= TEMPDIR(BOARD) * (OVERSAMPLENR);
  2319. #endif
  2320. #if HAS_TEMP_REDUNDANT
  2321. temp_redundant.target = &(
  2322. #if REDUNDANT_TEMP_MATCH(TARGET, COOLER) && HAS_TEMP_COOLER
  2323. temp_cooler
  2324. #elif REDUNDANT_TEMP_MATCH(TARGET, PROBE) && HAS_TEMP_PROBE
  2325. temp_probe
  2326. #elif REDUNDANT_TEMP_MATCH(TARGET, BOARD) && HAS_TEMP_BOARD
  2327. temp_board
  2328. #elif REDUNDANT_TEMP_MATCH(TARGET, CHAMBER) && HAS_TEMP_CHAMBER
  2329. temp_chamber
  2330. #elif REDUNDANT_TEMP_MATCH(TARGET, BED) && HAS_TEMP_BED
  2331. temp_bed
  2332. #else
  2333. temp_hotend[HEATER_ID(TEMP_SENSOR_REDUNDANT_TARGET)]
  2334. #endif
  2335. );
  2336. #endif
  2337. }
  2338. #if HAS_THERMAL_PROTECTION
  2339. #pragma GCC diagnostic push
  2340. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  2341. Temperature::tr_state_machine_t Temperature::tr_state_machine[NR_HEATER_RUNAWAY]; // = { { TRInactive, 0 } };
  2342. /**
  2343. * @brief Thermal Runaway state machine for a single heater
  2344. * @param current current measured temperature
  2345. * @param target current target temperature
  2346. * @param heater_id extruder index
  2347. * @param period_seconds missed temperature allowed time
  2348. * @param hysteresis_degc allowed distance from target
  2349. *
  2350. * TODO: Embed the last 3 parameters during init, if not less optimal
  2351. */
  2352. void Temperature::tr_state_machine_t::run(const_celsius_float_t current, const_celsius_float_t target, const heater_id_t heater_id, const uint16_t period_seconds, const celsius_t hysteresis_degc) {
  2353. #if HEATER_IDLE_HANDLER
  2354. // Convert the given heater_id_t to an idle array index
  2355. const IdleIndex idle_index = idle_index_for_id(heater_id);
  2356. #endif
  2357. /**
  2358. SERIAL_ECHO_START();
  2359. SERIAL_ECHOPGM("Thermal Runaway Running. Heater ID: ");
  2360. switch (heater_id) {
  2361. case H_BED: SERIAL_ECHOPGM("bed"); break;
  2362. case H_CHAMBER: SERIAL_ECHOPGM("chamber"); break;
  2363. default: SERIAL_ECHO(heater_id);
  2364. }
  2365. SERIAL_ECHOLNPGM(
  2366. " ; sizeof(running_temp):", sizeof(running_temp),
  2367. " ; State:", state, " ; Timer:", timer, " ; Temperature:", current, " ; Target Temp:", target
  2368. #if HEATER_IDLE_HANDLER
  2369. , " ; Idle Timeout:", heater_idle[idle_index].timed_out
  2370. #endif
  2371. );
  2372. */
  2373. #if ENABLED(THERMAL_PROTECTION_VARIANCE_MONITOR)
  2374. if (state == TRMalfunction) { // temperature invariance may continue, regardless of heater state
  2375. variance += ABS(current - last_temp); // no need for detection window now, a single change in variance is enough
  2376. last_temp = current;
  2377. if (!NEAR_ZERO(variance)) {
  2378. variance_timer = millis() + SEC_TO_MS(period_seconds);
  2379. variance = 0.0;
  2380. state = TRStable; // resume from where we detected the problem
  2381. }
  2382. }
  2383. #endif
  2384. if (TERN1(THERMAL_PROTECTION_VARIANCE_MONITOR, state != TRMalfunction)) {
  2385. // If the heater idle timeout expires, restart
  2386. if (TERN0(HEATER_IDLE_HANDLER, heater_idle[idle_index].timed_out)) {
  2387. state = TRInactive;
  2388. running_temp = 0;
  2389. TERN_(THERMAL_PROTECTION_VARIANCE_MONITOR, variance_timer = 0);
  2390. }
  2391. else if (running_temp != target) { // If the target temperature changes, restart
  2392. running_temp = target;
  2393. state = target > 0 ? TRFirstHeating : TRInactive;
  2394. TERN_(THERMAL_PROTECTION_VARIANCE_MONITOR, variance_timer = 0);
  2395. }
  2396. }
  2397. switch (state) {
  2398. // Inactive state waits for a target temperature to be set
  2399. case TRInactive: break;
  2400. // When first heating, wait for the temperature to be reached then go to Stable state
  2401. case TRFirstHeating:
  2402. if (current < running_temp) break;
  2403. state = TRStable;
  2404. // While the temperature is stable watch for a bad temperature
  2405. case TRStable: {
  2406. #if ENABLED(ADAPTIVE_FAN_SLOWING)
  2407. if (adaptive_fan_slowing && heater_id >= 0) {
  2408. const int fan_index = _MIN(heater_id, FAN_COUNT - 1);
  2409. if (fan_speed[fan_index] == 0 || current >= running_temp - (hysteresis_degc * 0.25f))
  2410. fan_speed_scaler[fan_index] = 128;
  2411. else if (current >= running_temp - (hysteresis_degc * 0.3335f))
  2412. fan_speed_scaler[fan_index] = 96;
  2413. else if (current >= running_temp - (hysteresis_degc * 0.5f))
  2414. fan_speed_scaler[fan_index] = 64;
  2415. else if (current >= running_temp - (hysteresis_degc * 0.8f))
  2416. fan_speed_scaler[fan_index] = 32;
  2417. else
  2418. fan_speed_scaler[fan_index] = 0;
  2419. }
  2420. #endif
  2421. const millis_t now = millis();
  2422. #if ENABLED(THERMAL_PROTECTION_VARIANCE_MONITOR)
  2423. if (PENDING(now, variance_timer)) {
  2424. variance += ABS(current - last_temp);
  2425. last_temp = current;
  2426. }
  2427. else {
  2428. if (NEAR_ZERO(variance) && variance_timer) { // valid variance monitoring window
  2429. state = TRMalfunction;
  2430. break;
  2431. }
  2432. variance_timer = now + SEC_TO_MS(period_seconds);
  2433. variance = 0.0;
  2434. last_temp = current;
  2435. }
  2436. #endif
  2437. if (current >= running_temp - hysteresis_degc) {
  2438. timer = now + SEC_TO_MS(period_seconds);
  2439. break;
  2440. }
  2441. else if (PENDING(now, timer)) break;
  2442. state = TRRunaway;
  2443. } // fall through
  2444. case TRRunaway:
  2445. TERN_(HAS_DWIN_E3V2_BASIC, DWIN_Popup_Temperature(0));
  2446. _temp_error(heater_id, FPSTR(str_t_thermal_runaway), GET_TEXT_F(MSG_THERMAL_RUNAWAY));
  2447. #if ENABLED(THERMAL_PROTECTION_VARIANCE_MONITOR)
  2448. case TRMalfunction:
  2449. TERN_(HAS_DWIN_E3V2_BASIC, DWIN_Popup_Temperature(0));
  2450. _temp_error(heater_id, FPSTR(str_t_temp_malfunction), GET_TEXT_F(MSG_TEMP_MALFUNCTION));
  2451. #endif
  2452. }
  2453. }
  2454. #pragma GCC diagnostic pop
  2455. #endif // HAS_THERMAL_PROTECTION
  2456. void Temperature::disable_all_heaters() {
  2457. // Disable autotemp, unpause and reset everything
  2458. TERN_(AUTOTEMP, planner.autotemp_enabled = false);
  2459. TERN_(PROBING_HEATERS_OFF, pause_heaters(false));
  2460. #if HAS_HOTEND
  2461. HOTEND_LOOP() {
  2462. setTargetHotend(0, e);
  2463. temp_hotend[e].soft_pwm_amount = 0;
  2464. }
  2465. #endif
  2466. #if HAS_TEMP_HOTEND
  2467. #define DISABLE_HEATER(N) WRITE_HEATER_##N(LOW);
  2468. REPEAT(HOTENDS, DISABLE_HEATER);
  2469. #endif
  2470. #if HAS_HEATED_BED
  2471. setTargetBed(0);
  2472. temp_bed.soft_pwm_amount = 0;
  2473. WRITE_HEATER_BED(LOW);
  2474. #endif
  2475. #if HAS_HEATED_CHAMBER
  2476. setTargetChamber(0);
  2477. temp_chamber.soft_pwm_amount = 0;
  2478. WRITE_HEATER_CHAMBER(LOW);
  2479. #endif
  2480. #if HAS_COOLER
  2481. setTargetCooler(0);
  2482. temp_cooler.soft_pwm_amount = 0;
  2483. WRITE_HEATER_COOLER(LOW);
  2484. #endif
  2485. }
  2486. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  2487. bool Temperature::auto_job_over_threshold() {
  2488. #if HAS_HOTEND
  2489. HOTEND_LOOP() if (degTargetHotend(e) > (EXTRUDE_MINTEMP) / 2) return true;
  2490. #endif
  2491. return TERN0(HAS_HEATED_BED, degTargetBed() > BED_MINTEMP)
  2492. || TERN0(HAS_HEATED_CHAMBER, degTargetChamber() > CHAMBER_MINTEMP);
  2493. }
  2494. void Temperature::auto_job_check_timer(const bool can_start, const bool can_stop) {
  2495. if (auto_job_over_threshold()) {
  2496. if (can_start) startOrResumeJob();
  2497. }
  2498. else if (can_stop) {
  2499. print_job_timer.stop();
  2500. ui.reset_status();
  2501. }
  2502. }
  2503. #endif // PRINTJOB_TIMER_AUTOSTART
  2504. #if ENABLED(PROBING_HEATERS_OFF)
  2505. void Temperature::pause_heaters(const bool p) {
  2506. if (p != paused_for_probing) {
  2507. paused_for_probing = p;
  2508. if (p) {
  2509. HOTEND_LOOP() heater_idle[e].expire(); // Timeout immediately
  2510. TERN_(HAS_HEATED_BED, heater_idle[IDLE_INDEX_BED].expire()); // Timeout immediately
  2511. }
  2512. else {
  2513. HOTEND_LOOP() reset_hotend_idle_timer(e);
  2514. TERN_(HAS_HEATED_BED, reset_bed_idle_timer());
  2515. }
  2516. }
  2517. }
  2518. #endif // PROBING_HEATERS_OFF
  2519. #if EITHER(SINGLENOZZLE_STANDBY_TEMP, SINGLENOZZLE_STANDBY_FAN)
  2520. void Temperature::singlenozzle_change(const uint8_t old_tool, const uint8_t new_tool) {
  2521. #if ENABLED(SINGLENOZZLE_STANDBY_FAN)
  2522. singlenozzle_fan_speed[old_tool] = fan_speed[0];
  2523. fan_speed[0] = singlenozzle_fan_speed[new_tool];
  2524. #endif
  2525. #if ENABLED(SINGLENOZZLE_STANDBY_TEMP)
  2526. singlenozzle_temp[old_tool] = temp_hotend[0].target;
  2527. if (singlenozzle_temp[new_tool] && singlenozzle_temp[new_tool] != singlenozzle_temp[old_tool]) {
  2528. setTargetHotend(singlenozzle_temp[new_tool], 0);
  2529. TERN_(AUTOTEMP, planner.autotemp_update());
  2530. set_heating_message(0);
  2531. (void)wait_for_hotend(0, false); // Wait for heating or cooling
  2532. }
  2533. #endif
  2534. }
  2535. #endif // SINGLENOZZLE_STANDBY_TEMP || SINGLENOZZLE_STANDBY_FAN
  2536. #if HAS_MAX_TC
  2537. #ifndef THERMOCOUPLE_MAX_ERRORS
  2538. #define THERMOCOUPLE_MAX_ERRORS 15
  2539. #endif
  2540. /**
  2541. * @brief Read MAX Thermocouple temperature.
  2542. *
  2543. * Reads the thermocouple board via HW or SW SPI, using a library (LIB_USR_x) or raw SPI reads.
  2544. * Doesn't strictly return a temperature; returns an "ADC Value" (i.e. raw register content).
  2545. *
  2546. * @param hindex the hotend we're referencing (if MULTI_MAX_TC)
  2547. * @return integer representing the board's buffer, to be converted later if needed
  2548. */
  2549. raw_adc_t Temperature::read_max_tc(TERN_(HAS_MULTI_MAX_TC, const uint8_t hindex/*=0*/)) {
  2550. #define MAXTC_HEAT_INTERVAL 250UL
  2551. #if HAS_MAX31855
  2552. #define MAX_TC_ERROR_MASK 7 // D2-0: SCV, SCG, OC
  2553. #define MAX_TC_DISCARD_BITS 18 // Data D31-18; sign bit D31
  2554. #define MAX_TC_SPEED_BITS 3 // ~1MHz
  2555. #elif HAS_MAX31865
  2556. #define MAX_TC_ERROR_MASK 1 // D0 Bit on fault only
  2557. #define MAX_TC_DISCARD_BITS 1 // Data is in D15-D1
  2558. #define MAX_TC_SPEED_BITS 3 // ~1MHz
  2559. #else // MAX6675
  2560. #define MAX_TC_ERROR_MASK 3 // D2 only; 1 = open circuit
  2561. #define MAX_TC_DISCARD_BITS 3 // Data D15-D1
  2562. #define MAX_TC_SPEED_BITS 2 // ~2MHz
  2563. #endif
  2564. #if HAS_MULTI_MAX_TC
  2565. // Needed to return the correct temp when this is called between readings
  2566. static raw_adc_t max_tc_temp_previous[MAX_TC_COUNT] = { 0 };
  2567. #define THERMO_TEMP(I) max_tc_temp_previous[I]
  2568. #define THERMO_SEL(A,B) (hindex ? (B) : (A))
  2569. #define MAXTC_CS_WRITE(V) do{ switch (hindex) { case 1: WRITE(TEMP_1_CS_PIN, V); break; default: WRITE(TEMP_0_CS_PIN, V); } }while(0)
  2570. #else
  2571. // When we have only 1 max tc, THERMO_SEL will pick the appropriate sensor
  2572. // variable, and MAXTC_*() macros will be hardcoded to the correct CS pin.
  2573. constexpr uint8_t hindex = 0;
  2574. #define THERMO_TEMP(I) max_tc_temp
  2575. #if TEMP_SENSOR_IS_ANY_MAX_TC(0)
  2576. #define THERMO_SEL(A,B) A
  2577. #define MAXTC_CS_WRITE(V) WRITE(TEMP_0_CS_PIN, V)
  2578. #else
  2579. #define THERMO_SEL(A,B) B
  2580. #define MAXTC_CS_WRITE(V) WRITE(TEMP_1_CS_PIN, V)
  2581. #endif
  2582. #endif
  2583. static TERN(HAS_MAX31855, uint32_t, uint16_t) max_tc_temp = THERMO_SEL(
  2584. TEMP_SENSOR_0_MAX_TC_TMAX,
  2585. TEMP_SENSOR_1_MAX_TC_TMAX
  2586. );
  2587. static uint8_t max_tc_errors[MAX_TC_COUNT] = { 0 };
  2588. static millis_t next_max_tc_ms[MAX_TC_COUNT] = { 0 };
  2589. // Return last-read value between readings
  2590. const millis_t ms = millis();
  2591. if (PENDING(ms, next_max_tc_ms[hindex]))
  2592. return THERMO_TEMP(hindex);
  2593. next_max_tc_ms[hindex] = ms + MAXTC_HEAT_INTERVAL;
  2594. #if !HAS_MAXTC_LIBRARIES
  2595. max_tc_temp = 0;
  2596. #if !HAS_MAXTC_SW_SPI
  2597. // Initialize SPI using the default Hardware SPI bus.
  2598. // FIXME: spiBegin, spiRec and spiInit doesn't work when soft spi is used.
  2599. spiBegin();
  2600. spiInit(MAX_TC_SPEED_BITS);
  2601. #endif
  2602. MAXTC_CS_WRITE(LOW); // Enable MAXTC
  2603. DELAY_NS(100); // Ensure 100ns delay
  2604. // Read a big-endian temperature value without using a library
  2605. for (uint8_t i = sizeof(max_tc_temp); i--;) {
  2606. max_tc_temp |= TERN(HAS_MAXTC_SW_SPI, max_tc_spi.receive(), spiRec());
  2607. if (i > 0) max_tc_temp <<= 8; // shift left if not the last byte
  2608. }
  2609. MAXTC_CS_WRITE(HIGH); // Disable MAXTC
  2610. #else
  2611. #if HAS_MAX6675_LIBRARY
  2612. MAX6675 &max6675ref = THERMO_SEL(max6675_0, max6675_1);
  2613. max_tc_temp = max6675ref.readRaw16();
  2614. #endif
  2615. #if HAS_MAX31855_LIBRARY
  2616. MAX31855 &max855ref = THERMO_SEL(max31855_0, max31855_1);
  2617. max_tc_temp = max855ref.readRaw32();
  2618. #endif
  2619. #if HAS_MAX31865
  2620. MAX31865 &max865ref = THERMO_SEL(max31865_0, max31865_1);
  2621. max_tc_temp = TERN(LIB_INTERNAL_MAX31865, max865ref.readRaw(), max865ref.readRTD_with_Fault());
  2622. #endif
  2623. #endif
  2624. // Handle an error. If there have been more than THERMOCOUPLE_MAX_ERRORS, send an error over serial.
  2625. // Either way, return the TMAX for the thermocouple to trigger a max_temp_error()
  2626. if (max_tc_temp & MAX_TC_ERROR_MASK) {
  2627. max_tc_errors[hindex]++;
  2628. if (max_tc_errors[hindex] > THERMOCOUPLE_MAX_ERRORS) {
  2629. SERIAL_ERROR_START();
  2630. SERIAL_ECHOPGM("Temp measurement error! ");
  2631. #if HAS_MAX31855
  2632. SERIAL_ECHOPGM("MAX31855 Fault: (", max_tc_temp & 0x7, ") >> ");
  2633. if (max_tc_temp & 0x1)
  2634. SERIAL_ECHOLNPGM("Open Circuit");
  2635. else if (max_tc_temp & 0x2)
  2636. SERIAL_ECHOLNPGM("Short to GND");
  2637. else if (max_tc_temp & 0x4)
  2638. SERIAL_ECHOLNPGM("Short to VCC");
  2639. #elif HAS_MAX31865
  2640. const uint8_t fault_31865 = max865ref.readFault();
  2641. max865ref.clearFault();
  2642. if (fault_31865) {
  2643. SERIAL_EOL();
  2644. SERIAL_ECHOLNPGM("\nMAX31865 Fault: (", fault_31865, ") >>");
  2645. if (fault_31865 & MAX31865_FAULT_HIGHTHRESH)
  2646. SERIAL_ECHOLNPGM("RTD High Threshold");
  2647. if (fault_31865 & MAX31865_FAULT_LOWTHRESH)
  2648. SERIAL_ECHOLNPGM("RTD Low Threshold");
  2649. if (fault_31865 & MAX31865_FAULT_REFINLOW)
  2650. SERIAL_ECHOLNPGM("REFIN- > 0.85 x V bias");
  2651. if (fault_31865 & MAX31865_FAULT_REFINHIGH)
  2652. SERIAL_ECHOLNPGM("REFIN- < 0.85 x V bias (FORCE- open)");
  2653. if (fault_31865 & MAX31865_FAULT_RTDINLOW)
  2654. SERIAL_ECHOLNPGM("REFIN- < 0.85 x V bias (FORCE- open)");
  2655. if (fault_31865 & MAX31865_FAULT_OVUV)
  2656. SERIAL_ECHOLNPGM("Under/Over voltage");
  2657. }
  2658. #else // MAX6675
  2659. SERIAL_ECHOLNPGM("MAX6675 Fault: Open Circuit");
  2660. #endif
  2661. // Set thermocouple above max temperature (TMAX)
  2662. max_tc_temp = THERMO_SEL(TEMP_SENSOR_0_MAX_TC_TMAX, TEMP_SENSOR_1_MAX_TC_TMAX) << (MAX_TC_DISCARD_BITS + 1);
  2663. }
  2664. }
  2665. else {
  2666. max_tc_errors[hindex] = 0; // No error bit, reset error count
  2667. }
  2668. max_tc_temp >>= MAX_TC_DISCARD_BITS;
  2669. #if HAS_MAX31855
  2670. // Support negative temperature for MAX38155
  2671. if (max_tc_temp & 0x00002000) max_tc_temp |= 0xFFFFC000;
  2672. #endif
  2673. THERMO_TEMP(hindex) = max_tc_temp;
  2674. return max_tc_temp;
  2675. }
  2676. #endif // HAS_MAX_TC
  2677. /**
  2678. * Update raw temperatures
  2679. *
  2680. * Called by ISR => readings_ready when new temperatures have been set by updateTemperaturesFromRawValues.
  2681. * Applies all the accumulators to the current raw temperatures.
  2682. */
  2683. void Temperature::update_raw_temperatures() {
  2684. // TODO: can this be collapsed into a HOTEND_LOOP()?
  2685. #if HAS_TEMP_ADC_0 && !TEMP_SENSOR_0_IS_MAX_TC
  2686. temp_hotend[0].update();
  2687. #endif
  2688. #if HAS_TEMP_ADC_1 && !TEMP_SENSOR_1_IS_MAX_TC
  2689. temp_hotend[1].update();
  2690. #endif
  2691. #if HAS_TEMP_ADC_REDUNDANT && !TEMP_SENSOR_REDUNDANT_IS_MAX_TC
  2692. temp_redundant.update();
  2693. #endif
  2694. TERN_(HAS_TEMP_ADC_2, temp_hotend[2].update());
  2695. TERN_(HAS_TEMP_ADC_3, temp_hotend[3].update());
  2696. TERN_(HAS_TEMP_ADC_4, temp_hotend[4].update());
  2697. TERN_(HAS_TEMP_ADC_5, temp_hotend[5].update());
  2698. TERN_(HAS_TEMP_ADC_6, temp_hotend[6].update());
  2699. TERN_(HAS_TEMP_ADC_7, temp_hotend[7].update());
  2700. TERN_(HAS_TEMP_ADC_BED, temp_bed.update());
  2701. TERN_(HAS_TEMP_ADC_CHAMBER, temp_chamber.update());
  2702. TERN_(HAS_TEMP_ADC_PROBE, temp_probe.update());
  2703. TERN_(HAS_TEMP_ADC_COOLER, temp_cooler.update());
  2704. TERN_(HAS_TEMP_ADC_BOARD, temp_board.update());
  2705. TERN_(HAS_JOY_ADC_X, joystick.x.update());
  2706. TERN_(HAS_JOY_ADC_Y, joystick.y.update());
  2707. TERN_(HAS_JOY_ADC_Z, joystick.z.update());
  2708. }
  2709. /**
  2710. * Called by the Temperature ISR when all the ADCs have been processed.
  2711. * Reset all the ADC accumulators for another round of updates.
  2712. */
  2713. void Temperature::readings_ready() {
  2714. // Update raw values only if they're not already set.
  2715. if (!raw_temps_ready) {
  2716. update_raw_temperatures();
  2717. raw_temps_ready = true;
  2718. }
  2719. // Filament Sensor - can be read any time since IIR filtering is used
  2720. TERN_(FILAMENT_WIDTH_SENSOR, filwidth.reading_ready());
  2721. #if HAS_HOTEND
  2722. HOTEND_LOOP() temp_hotend[e].reset();
  2723. #endif
  2724. TERN_(HAS_HEATED_BED, temp_bed.reset());
  2725. TERN_(HAS_TEMP_CHAMBER, temp_chamber.reset());
  2726. TERN_(HAS_TEMP_PROBE, temp_probe.reset());
  2727. TERN_(HAS_TEMP_COOLER, temp_cooler.reset());
  2728. TERN_(HAS_TEMP_BOARD, temp_board.reset());
  2729. TERN_(HAS_TEMP_REDUNDANT, temp_redundant.reset());
  2730. TERN_(HAS_JOY_ADC_X, joystick.x.reset());
  2731. TERN_(HAS_JOY_ADC_Y, joystick.y.reset());
  2732. TERN_(HAS_JOY_ADC_Z, joystick.z.reset());
  2733. }
  2734. /**
  2735. * Timer 0 is shared with millies so don't change the prescaler.
  2736. *
  2737. * On AVR this ISR uses the compare method so it runs at the base
  2738. * frequency (16 MHz / 64 / 256 = 976.5625 Hz), but at the TCNT0 set
  2739. * in OCR0B above (128 or halfway between OVFs).
  2740. *
  2741. * - Manage PWM to all the heaters and fan
  2742. * - Prepare or Measure one of the raw ADC sensor values
  2743. * - Check new temperature values for MIN/MAX errors (kill on error)
  2744. * - Step the babysteps value for each axis towards 0
  2745. * - For PINS_DEBUGGING, monitor and report endstop pins
  2746. * - For ENDSTOP_INTERRUPTS_FEATURE check endstops if flagged
  2747. * - Call planner.isr to count down its "ignore" time
  2748. */
  2749. HAL_TEMP_TIMER_ISR() {
  2750. HAL_timer_isr_prologue(MF_TIMER_TEMP);
  2751. Temperature::isr();
  2752. HAL_timer_isr_epilogue(MF_TIMER_TEMP);
  2753. }
  2754. #if ENABLED(SLOW_PWM_HEATERS) && !defined(MIN_STATE_TIME)
  2755. #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
  2756. #endif
  2757. class SoftPWM {
  2758. public:
  2759. uint8_t count;
  2760. inline bool add(const uint8_t mask, const uint8_t amount) {
  2761. count = (count & mask) + amount; return (count > mask);
  2762. }
  2763. #if ENABLED(SLOW_PWM_HEATERS)
  2764. bool state_heater;
  2765. uint8_t state_timer_heater;
  2766. inline void dec() { if (state_timer_heater > 0) state_timer_heater--; }
  2767. inline bool ready(const bool v) {
  2768. const bool rdy = !state_timer_heater;
  2769. if (rdy && state_heater != v) {
  2770. state_heater = v;
  2771. state_timer_heater = MIN_STATE_TIME;
  2772. }
  2773. return rdy;
  2774. }
  2775. #endif
  2776. };
  2777. /**
  2778. * Handle various ~1kHz tasks associated with temperature
  2779. * - Check laser safety timeout
  2780. * - Heater PWM (~1kHz with scaler)
  2781. * - LCD Button polling (~500Hz)
  2782. * - Start / Read one ADC sensor
  2783. * - Advance Babysteps
  2784. * - Endstop polling
  2785. * - Planner clean buffer
  2786. */
  2787. void Temperature::isr() {
  2788. // Shut down the laser if steppers are inactive for > LASER_SAFETY_TIMEOUT_MS ms
  2789. #if LASER_SAFETY_TIMEOUT_MS > 0
  2790. if (cutter.last_power_applied && ELAPSED(millis(), gcode.previous_move_ms + (LASER_SAFETY_TIMEOUT_MS))) {
  2791. cutter.power = 0; // Prevent planner idle from re-enabling power
  2792. cutter.apply_power(0);
  2793. }
  2794. #endif
  2795. static int8_t temp_count = -1;
  2796. static ADCSensorState adc_sensor_state = StartupDelay;
  2797. static uint8_t pwm_count = _BV(SOFT_PWM_SCALE);
  2798. // Avoid multiple loads of pwm_count
  2799. uint8_t pwm_count_tmp = pwm_count;
  2800. #if HAS_ADC_BUTTONS
  2801. static raw_adc_t raw_ADCKey_value = 0;
  2802. static bool ADCKey_pressed = false;
  2803. #endif
  2804. #if HAS_HOTEND
  2805. static SoftPWM soft_pwm_hotend[HOTENDS];
  2806. #endif
  2807. #if HAS_HEATED_BED
  2808. static SoftPWM soft_pwm_bed;
  2809. #endif
  2810. #if HAS_HEATED_CHAMBER
  2811. static SoftPWM soft_pwm_chamber;
  2812. #endif
  2813. #if HAS_COOLER
  2814. static SoftPWM soft_pwm_cooler;
  2815. #endif
  2816. #if BOTH(FAN_SOFT_PWM, USE_CONTROLLER_FAN)
  2817. static SoftPWM soft_pwm_controller;
  2818. #endif
  2819. #define WRITE_FAN(n, v) WRITE(FAN##n##_PIN, (v) ^ FAN_INVERTING)
  2820. #if DISABLED(SLOW_PWM_HEATERS)
  2821. #if ANY(HAS_HOTEND, HAS_HEATED_BED, HAS_HEATED_CHAMBER, HAS_COOLER, FAN_SOFT_PWM)
  2822. constexpr uint8_t pwm_mask = TERN0(SOFT_PWM_DITHER, _BV(SOFT_PWM_SCALE) - 1);
  2823. #define _PWM_MOD(N,S,T) do{ \
  2824. const bool on = S.add(pwm_mask, T.soft_pwm_amount); \
  2825. WRITE_HEATER_##N(on); \
  2826. }while(0)
  2827. #endif
  2828. /**
  2829. * Standard heater PWM modulation
  2830. */
  2831. if (pwm_count_tmp >= 127) {
  2832. pwm_count_tmp -= 127;
  2833. #if HAS_HOTEND
  2834. #define _PWM_MOD_E(N) _PWM_MOD(N,soft_pwm_hotend[N],temp_hotend[N]);
  2835. REPEAT(HOTENDS, _PWM_MOD_E);
  2836. #endif
  2837. #if HAS_HEATED_BED
  2838. _PWM_MOD(BED, soft_pwm_bed, temp_bed);
  2839. #endif
  2840. #if HAS_HEATED_CHAMBER
  2841. _PWM_MOD(CHAMBER, soft_pwm_chamber, temp_chamber);
  2842. #endif
  2843. #if HAS_COOLER
  2844. _PWM_MOD(COOLER, soft_pwm_cooler, temp_cooler);
  2845. #endif
  2846. #if ENABLED(FAN_SOFT_PWM)
  2847. #if ENABLED(USE_CONTROLLER_FAN)
  2848. WRITE(CONTROLLER_FAN_PIN, soft_pwm_controller.add(pwm_mask, soft_pwm_controller_speed));
  2849. #endif
  2850. #define _FAN_PWM(N) do{ \
  2851. uint8_t &spcf = soft_pwm_count_fan[N]; \
  2852. spcf = (spcf & pwm_mask) + (soft_pwm_amount_fan[N] >> 1); \
  2853. WRITE_FAN(N, spcf > pwm_mask ? HIGH : LOW); \
  2854. }while(0)
  2855. #if HAS_FAN0
  2856. _FAN_PWM(0);
  2857. #endif
  2858. #if HAS_FAN1
  2859. _FAN_PWM(1);
  2860. #endif
  2861. #if HAS_FAN2
  2862. _FAN_PWM(2);
  2863. #endif
  2864. #if HAS_FAN3
  2865. _FAN_PWM(3);
  2866. #endif
  2867. #if HAS_FAN4
  2868. _FAN_PWM(4);
  2869. #endif
  2870. #if HAS_FAN5
  2871. _FAN_PWM(5);
  2872. #endif
  2873. #if HAS_FAN6
  2874. _FAN_PWM(6);
  2875. #endif
  2876. #if HAS_FAN7
  2877. _FAN_PWM(7);
  2878. #endif
  2879. #endif
  2880. }
  2881. else {
  2882. #define _PWM_LOW(N,S) do{ if (S.count <= pwm_count_tmp) WRITE_HEATER_##N(LOW); }while(0)
  2883. #if HAS_HOTEND
  2884. #define _PWM_LOW_E(N) _PWM_LOW(N, soft_pwm_hotend[N]);
  2885. REPEAT(HOTENDS, _PWM_LOW_E);
  2886. #endif
  2887. #if HAS_HEATED_BED
  2888. _PWM_LOW(BED, soft_pwm_bed);
  2889. #endif
  2890. #if HAS_HEATED_CHAMBER
  2891. _PWM_LOW(CHAMBER, soft_pwm_chamber);
  2892. #endif
  2893. #if HAS_COOLER
  2894. _PWM_LOW(COOLER, soft_pwm_cooler);
  2895. #endif
  2896. #if ENABLED(FAN_SOFT_PWM)
  2897. #if HAS_FAN0
  2898. if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(0, LOW);
  2899. #endif
  2900. #if HAS_FAN1
  2901. if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN(1, LOW);
  2902. #endif
  2903. #if HAS_FAN2
  2904. if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN(2, LOW);
  2905. #endif
  2906. #if HAS_FAN3
  2907. if (soft_pwm_count_fan[3] <= pwm_count_tmp) WRITE_FAN(3, LOW);
  2908. #endif
  2909. #if HAS_FAN4
  2910. if (soft_pwm_count_fan[4] <= pwm_count_tmp) WRITE_FAN(4, LOW);
  2911. #endif
  2912. #if HAS_FAN5
  2913. if (soft_pwm_count_fan[5] <= pwm_count_tmp) WRITE_FAN(5, LOW);
  2914. #endif
  2915. #if HAS_FAN6
  2916. if (soft_pwm_count_fan[6] <= pwm_count_tmp) WRITE_FAN(6, LOW);
  2917. #endif
  2918. #if HAS_FAN7
  2919. if (soft_pwm_count_fan[7] <= pwm_count_tmp) WRITE_FAN(7, LOW);
  2920. #endif
  2921. #if ENABLED(USE_CONTROLLER_FAN)
  2922. if (soft_pwm_controller.count <= pwm_count_tmp) WRITE(CONTROLLER_FAN_PIN, LOW);
  2923. #endif
  2924. #endif
  2925. }
  2926. // SOFT_PWM_SCALE to frequency:
  2927. //
  2928. // 0: 16000000/64/256/128 = 7.6294 Hz
  2929. // 1: / 64 = 15.2588 Hz
  2930. // 2: / 32 = 30.5176 Hz
  2931. // 3: / 16 = 61.0352 Hz
  2932. // 4: / 8 = 122.0703 Hz
  2933. // 5: / 4 = 244.1406 Hz
  2934. pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
  2935. #else // SLOW_PWM_HEATERS
  2936. /**
  2937. * SLOW PWM HEATERS
  2938. *
  2939. * For relay-driven heaters
  2940. */
  2941. #define _SLOW_SET(NR,PWM,V) do{ if (PWM.ready(V)) WRITE_HEATER_##NR(V); }while(0)
  2942. #define _SLOW_PWM(NR,PWM,SRC) do{ PWM.count = SRC.soft_pwm_amount; _SLOW_SET(NR,PWM,(PWM.count > 0)); }while(0)
  2943. #define _PWM_OFF(NR,PWM) do{ if (PWM.count < slow_pwm_count) _SLOW_SET(NR,PWM,0); }while(0)
  2944. static uint8_t slow_pwm_count = 0;
  2945. if (slow_pwm_count == 0) {
  2946. #if HAS_HOTEND
  2947. #define _SLOW_PWM_E(N) _SLOW_PWM(N, soft_pwm_hotend[N], temp_hotend[N]);
  2948. REPEAT(HOTENDS, _SLOW_PWM_E);
  2949. #endif
  2950. #if HAS_HEATED_BED
  2951. _SLOW_PWM(BED, soft_pwm_bed, temp_bed);
  2952. #endif
  2953. #if HAS_HEATED_CHAMBER
  2954. _SLOW_PWM(CHAMBER, soft_pwm_chamber, temp_chamber);
  2955. #endif
  2956. #if HAS_COOLER
  2957. _SLOW_PWM(COOLER, soft_pwm_cooler, temp_cooler);
  2958. #endif
  2959. } // slow_pwm_count == 0
  2960. #if HAS_HOTEND
  2961. #define _PWM_OFF_E(N) _PWM_OFF(N, soft_pwm_hotend[N]);
  2962. REPEAT(HOTENDS, _PWM_OFF_E);
  2963. #endif
  2964. #if HAS_HEATED_BED
  2965. _PWM_OFF(BED, soft_pwm_bed);
  2966. #endif
  2967. #if HAS_HEATED_CHAMBER
  2968. _PWM_OFF(CHAMBER, soft_pwm_chamber);
  2969. #endif
  2970. #if HAS_COOLER
  2971. _PWM_OFF(COOLER, soft_pwm_cooler, temp_cooler);
  2972. #endif
  2973. #if ENABLED(FAN_SOFT_PWM)
  2974. if (pwm_count_tmp >= 127) {
  2975. pwm_count_tmp = 0;
  2976. #define _PWM_FAN(N) do{ \
  2977. soft_pwm_count_fan[N] = soft_pwm_amount_fan[N] >> 1; \
  2978. WRITE_FAN(N, soft_pwm_count_fan[N] > 0 ? HIGH : LOW); \
  2979. }while(0)
  2980. #if HAS_FAN0
  2981. _PWM_FAN(0);
  2982. #endif
  2983. #if HAS_FAN1
  2984. _PWM_FAN(1);
  2985. #endif
  2986. #if HAS_FAN2
  2987. _PWM_FAN(2);
  2988. #endif
  2989. #if HAS_FAN3
  2990. _FAN_PWM(3);
  2991. #endif
  2992. #if HAS_FAN4
  2993. _FAN_PWM(4);
  2994. #endif
  2995. #if HAS_FAN5
  2996. _FAN_PWM(5);
  2997. #endif
  2998. #if HAS_FAN6
  2999. _FAN_PWM(6);
  3000. #endif
  3001. #if HAS_FAN7
  3002. _FAN_PWM(7);
  3003. #endif
  3004. }
  3005. #if HAS_FAN0
  3006. if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(0, LOW);
  3007. #endif
  3008. #if HAS_FAN1
  3009. if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN(1, LOW);
  3010. #endif
  3011. #if HAS_FAN2
  3012. if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN(2, LOW);
  3013. #endif
  3014. #if HAS_FAN3
  3015. if (soft_pwm_count_fan[3] <= pwm_count_tmp) WRITE_FAN(3, LOW);
  3016. #endif
  3017. #if HAS_FAN4
  3018. if (soft_pwm_count_fan[4] <= pwm_count_tmp) WRITE_FAN(4, LOW);
  3019. #endif
  3020. #if HAS_FAN5
  3021. if (soft_pwm_count_fan[5] <= pwm_count_tmp) WRITE_FAN(5, LOW);
  3022. #endif
  3023. #if HAS_FAN6
  3024. if (soft_pwm_count_fan[6] <= pwm_count_tmp) WRITE_FAN(6, LOW);
  3025. #endif
  3026. #if HAS_FAN7
  3027. if (soft_pwm_count_fan[7] <= pwm_count_tmp) WRITE_FAN(7, LOW);
  3028. #endif
  3029. #endif // FAN_SOFT_PWM
  3030. // SOFT_PWM_SCALE to frequency:
  3031. //
  3032. // 0: 16000000/64/256/128 = 7.6294 Hz
  3033. // 1: / 64 = 15.2588 Hz
  3034. // 2: / 32 = 30.5176 Hz
  3035. // 3: / 16 = 61.0352 Hz
  3036. // 4: / 8 = 122.0703 Hz
  3037. // 5: / 4 = 244.1406 Hz
  3038. pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
  3039. // Increment slow_pwm_count only every 64th pwm_count,
  3040. // i.e., yielding a PWM frequency of 16/128 Hz (8s).
  3041. if (((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0) {
  3042. slow_pwm_count++;
  3043. slow_pwm_count &= 0x7F;
  3044. #if HAS_HOTEND
  3045. HOTEND_LOOP() soft_pwm_hotend[e].dec();
  3046. #endif
  3047. TERN_(HAS_HEATED_BED, soft_pwm_bed.dec());
  3048. TERN_(HAS_HEATED_CHAMBER, soft_pwm_chamber.dec());
  3049. TERN_(HAS_COOLER, soft_pwm_cooler.dec());
  3050. }
  3051. #endif // SLOW_PWM_HEATERS
  3052. //
  3053. // Update lcd buttons 488 times per second
  3054. //
  3055. static bool do_buttons;
  3056. if ((do_buttons ^= true)) ui.update_buttons();
  3057. /**
  3058. * One sensor is sampled on every other call of the ISR.
  3059. * Each sensor is read 16 (OVERSAMPLENR) times, taking the average.
  3060. *
  3061. * On each Prepare pass, ADC is started for a sensor pin.
  3062. * On the next pass, the ADC value is read and accumulated.
  3063. *
  3064. * This gives each ADC 0.9765ms to charge up.
  3065. */
  3066. #define ACCUMULATE_ADC(obj) do{ \
  3067. if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; \
  3068. else obj.sample(hal.adc_value()); \
  3069. }while(0)
  3070. ADCSensorState next_sensor_state = adc_sensor_state < SensorsReady ? (ADCSensorState)(int(adc_sensor_state) + 1) : StartSampling;
  3071. switch (adc_sensor_state) {
  3072. #pragma GCC diagnostic push
  3073. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  3074. case SensorsReady: {
  3075. // All sensors have been read. Stay in this state for a few
  3076. // ISRs to save on calls to temp update/checking code below.
  3077. constexpr int8_t extra_loops = MIN_ADC_ISR_LOOPS - (int8_t)SensorsReady;
  3078. static uint8_t delay_count = 0;
  3079. if (extra_loops > 0) {
  3080. if (delay_count == 0) delay_count = extra_loops; // Init this delay
  3081. if (--delay_count) // While delaying...
  3082. next_sensor_state = SensorsReady; // retain this state (else, next state will be 0)
  3083. break;
  3084. }
  3085. else {
  3086. adc_sensor_state = StartSampling; // Fall-through to start sampling
  3087. next_sensor_state = (ADCSensorState)(int(StartSampling) + 1);
  3088. }
  3089. }
  3090. #pragma GCC diagnostic pop
  3091. case StartSampling: // Start of sampling loops. Do updates/checks.
  3092. if (++temp_count >= OVERSAMPLENR) { // 10 * 16 * 1/(16000000/64/256) = 164ms.
  3093. temp_count = 0;
  3094. readings_ready();
  3095. }
  3096. break;
  3097. #if HAS_TEMP_ADC_0
  3098. case PrepareTemp_0: hal.adc_start(TEMP_0_PIN); break;
  3099. case MeasureTemp_0: ACCUMULATE_ADC(temp_hotend[0]); break;
  3100. #endif
  3101. #if HAS_TEMP_ADC_BED
  3102. case PrepareTemp_BED: hal.adc_start(TEMP_BED_PIN); break;
  3103. case MeasureTemp_BED: ACCUMULATE_ADC(temp_bed); break;
  3104. #endif
  3105. #if HAS_TEMP_ADC_CHAMBER
  3106. case PrepareTemp_CHAMBER: hal.adc_start(TEMP_CHAMBER_PIN); break;
  3107. case MeasureTemp_CHAMBER: ACCUMULATE_ADC(temp_chamber); break;
  3108. #endif
  3109. #if HAS_TEMP_ADC_COOLER
  3110. case PrepareTemp_COOLER: hal.adc_start(TEMP_COOLER_PIN); break;
  3111. case MeasureTemp_COOLER: ACCUMULATE_ADC(temp_cooler); break;
  3112. #endif
  3113. #if HAS_TEMP_ADC_PROBE
  3114. case PrepareTemp_PROBE: hal.adc_start(TEMP_PROBE_PIN); break;
  3115. case MeasureTemp_PROBE: ACCUMULATE_ADC(temp_probe); break;
  3116. #endif
  3117. #if HAS_TEMP_ADC_BOARD
  3118. case PrepareTemp_BOARD: hal.adc_start(TEMP_BOARD_PIN); break;
  3119. case MeasureTemp_BOARD: ACCUMULATE_ADC(temp_board); break;
  3120. #endif
  3121. #if HAS_TEMP_ADC_REDUNDANT
  3122. case PrepareTemp_REDUNDANT: hal.adc_start(TEMP_REDUNDANT_PIN); break;
  3123. case MeasureTemp_REDUNDANT: ACCUMULATE_ADC(temp_redundant); break;
  3124. #endif
  3125. #if HAS_TEMP_ADC_1
  3126. case PrepareTemp_1: hal.adc_start(TEMP_1_PIN); break;
  3127. case MeasureTemp_1: ACCUMULATE_ADC(temp_hotend[1]); break;
  3128. #endif
  3129. #if HAS_TEMP_ADC_2
  3130. case PrepareTemp_2: hal.adc_start(TEMP_2_PIN); break;
  3131. case MeasureTemp_2: ACCUMULATE_ADC(temp_hotend[2]); break;
  3132. #endif
  3133. #if HAS_TEMP_ADC_3
  3134. case PrepareTemp_3: hal.adc_start(TEMP_3_PIN); break;
  3135. case MeasureTemp_3: ACCUMULATE_ADC(temp_hotend[3]); break;
  3136. #endif
  3137. #if HAS_TEMP_ADC_4
  3138. case PrepareTemp_4: hal.adc_start(TEMP_4_PIN); break;
  3139. case MeasureTemp_4: ACCUMULATE_ADC(temp_hotend[4]); break;
  3140. #endif
  3141. #if HAS_TEMP_ADC_5
  3142. case PrepareTemp_5: hal.adc_start(TEMP_5_PIN); break;
  3143. case MeasureTemp_5: ACCUMULATE_ADC(temp_hotend[5]); break;
  3144. #endif
  3145. #if HAS_TEMP_ADC_6
  3146. case PrepareTemp_6: hal.adc_start(TEMP_6_PIN); break;
  3147. case MeasureTemp_6: ACCUMULATE_ADC(temp_hotend[6]); break;
  3148. #endif
  3149. #if HAS_TEMP_ADC_7
  3150. case PrepareTemp_7: hal.adc_start(TEMP_7_PIN); break;
  3151. case MeasureTemp_7: ACCUMULATE_ADC(temp_hotend[7]); break;
  3152. #endif
  3153. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  3154. case Prepare_FILWIDTH: hal.adc_start(FILWIDTH_PIN); break;
  3155. case Measure_FILWIDTH:
  3156. if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; // Redo this state
  3157. else filwidth.accumulate(hal.adc_value());
  3158. break;
  3159. #endif
  3160. #if ENABLED(POWER_MONITOR_CURRENT)
  3161. case Prepare_POWER_MONITOR_CURRENT:
  3162. hal.adc_start(POWER_MONITOR_CURRENT_PIN);
  3163. break;
  3164. case Measure_POWER_MONITOR_CURRENT:
  3165. if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; // Redo this state
  3166. else power_monitor.add_current_sample(hal.adc_value());
  3167. break;
  3168. #endif
  3169. #if ENABLED(POWER_MONITOR_VOLTAGE)
  3170. case Prepare_POWER_MONITOR_VOLTAGE:
  3171. hal.adc_start(POWER_MONITOR_VOLTAGE_PIN);
  3172. break;
  3173. case Measure_POWER_MONITOR_VOLTAGE:
  3174. if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; // Redo this state
  3175. else power_monitor.add_voltage_sample(hal.adc_value());
  3176. break;
  3177. #endif
  3178. #if HAS_JOY_ADC_X
  3179. case PrepareJoy_X: hal.adc_start(JOY_X_PIN); break;
  3180. case MeasureJoy_X: ACCUMULATE_ADC(joystick.x); break;
  3181. #endif
  3182. #if HAS_JOY_ADC_Y
  3183. case PrepareJoy_Y: hal.adc_start(JOY_Y_PIN); break;
  3184. case MeasureJoy_Y: ACCUMULATE_ADC(joystick.y); break;
  3185. #endif
  3186. #if HAS_JOY_ADC_Z
  3187. case PrepareJoy_Z: hal.adc_start(JOY_Z_PIN); break;
  3188. case MeasureJoy_Z: ACCUMULATE_ADC(joystick.z); break;
  3189. #endif
  3190. #if HAS_ADC_BUTTONS
  3191. #ifndef ADC_BUTTON_DEBOUNCE_DELAY
  3192. #define ADC_BUTTON_DEBOUNCE_DELAY 16
  3193. #endif
  3194. case Prepare_ADC_KEY: hal.adc_start(ADC_KEYPAD_PIN); break;
  3195. case Measure_ADC_KEY:
  3196. if (!hal.adc_ready())
  3197. next_sensor_state = adc_sensor_state; // redo this state
  3198. else if (ADCKey_count < ADC_BUTTON_DEBOUNCE_DELAY) {
  3199. raw_ADCKey_value = hal.adc_value();
  3200. if (raw_ADCKey_value <= 900UL * HAL_ADC_RANGE / 1024UL) {
  3201. NOMORE(current_ADCKey_raw, raw_ADCKey_value);
  3202. ADCKey_count++;
  3203. }
  3204. else { //ADC Key release
  3205. if (ADCKey_count > 0) ADCKey_count++; else ADCKey_pressed = false;
  3206. if (ADCKey_pressed) {
  3207. ADCKey_count = 0;
  3208. current_ADCKey_raw = HAL_ADC_RANGE;
  3209. }
  3210. }
  3211. }
  3212. if (ADCKey_count == ADC_BUTTON_DEBOUNCE_DELAY) ADCKey_pressed = true;
  3213. break;
  3214. #endif // HAS_ADC_BUTTONS
  3215. case StartupDelay: break;
  3216. } // switch(adc_sensor_state)
  3217. // Go to the next state
  3218. adc_sensor_state = next_sensor_state;
  3219. //
  3220. // Additional ~1kHz Tasks
  3221. //
  3222. #if ENABLED(BABYSTEPPING) && DISABLED(INTEGRATED_BABYSTEPPING)
  3223. babystep.task();
  3224. #endif
  3225. // Check fan tachometers
  3226. TERN_(HAS_FANCHECK, fan_check.update_tachometers());
  3227. // Poll endstops state, if required
  3228. endstops.poll();
  3229. // Periodically call the planner timer service routine
  3230. planner.isr();
  3231. }
  3232. #if HAS_TEMP_SENSOR
  3233. /**
  3234. * Print a single heater state in the form:
  3235. * Bed: " B:nnn.nn /nnn.nn"
  3236. * Chamber: " C:nnn.nn /nnn.nn"
  3237. * Probe: " P:nnn.nn /nnn.nn"
  3238. * Cooler: " L:nnn.nn /nnn.nn"
  3239. * Redundant: " R:nnn.nn /nnn.nn"
  3240. * Extruder: " T0:nnn.nn /nnn.nn"
  3241. * With ADC: " T0:nnn.nn /nnn.nn (nnn.nn)"
  3242. */
  3243. static void print_heater_state(const heater_id_t e, const_celsius_float_t c, const_celsius_float_t t
  3244. OPTARG(SHOW_TEMP_ADC_VALUES, const float r)
  3245. ) {
  3246. char k;
  3247. switch (e) {
  3248. default:
  3249. #if HAS_TEMP_HOTEND
  3250. k = 'T'; break;
  3251. #endif
  3252. #if HAS_TEMP_BED
  3253. case H_BED: k = 'B'; break;
  3254. #endif
  3255. #if HAS_TEMP_CHAMBER
  3256. case H_CHAMBER: k = 'C'; break;
  3257. #endif
  3258. #if HAS_TEMP_PROBE
  3259. case H_PROBE: k = 'P'; break;
  3260. #endif
  3261. #if HAS_TEMP_COOLER
  3262. case H_COOLER: k = 'L'; break;
  3263. #endif
  3264. #if HAS_TEMP_BOARD
  3265. case H_BOARD: k = 'M'; break;
  3266. #endif
  3267. #if HAS_TEMP_REDUNDANT
  3268. case H_REDUNDANT: k = 'R'; break;
  3269. #endif
  3270. }
  3271. SERIAL_CHAR(' ', k);
  3272. #if HAS_MULTI_HOTEND
  3273. if (e >= 0) SERIAL_CHAR('0' + e);
  3274. #endif
  3275. #ifdef SERIAL_FLOAT_PRECISION
  3276. #define SFP _MIN(SERIAL_FLOAT_PRECISION, 2)
  3277. #else
  3278. #define SFP 2
  3279. #endif
  3280. SERIAL_CHAR(':');
  3281. SERIAL_PRINT(c, SFP);
  3282. SERIAL_ECHOPGM(" /");
  3283. SERIAL_PRINT(t, SFP);
  3284. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  3285. // Temperature MAX SPI boards do not have an OVERSAMPLENR defined
  3286. SERIAL_ECHOPGM(" (", TERN(HAS_MAXTC_LIBRARIES, k == 'T', false) ? r : r * RECIPROCAL(OVERSAMPLENR));
  3287. SERIAL_CHAR(')');
  3288. #endif
  3289. delay(2);
  3290. }
  3291. void Temperature::print_heater_states(const int8_t target_extruder
  3292. OPTARG(HAS_TEMP_REDUNDANT, const bool include_r/*=false*/)
  3293. ) {
  3294. #if HAS_TEMP_HOTEND
  3295. print_heater_state(H_NONE, degHotend(target_extruder), degTargetHotend(target_extruder) OPTARG(SHOW_TEMP_ADC_VALUES, rawHotendTemp(target_extruder)));
  3296. #endif
  3297. #if HAS_HEATED_BED
  3298. print_heater_state(H_BED, degBed(), degTargetBed() OPTARG(SHOW_TEMP_ADC_VALUES, rawBedTemp()));
  3299. #endif
  3300. #if HAS_TEMP_CHAMBER
  3301. print_heater_state(H_CHAMBER, degChamber(), TERN0(HAS_HEATED_CHAMBER, degTargetChamber()) OPTARG(SHOW_TEMP_ADC_VALUES, rawChamberTemp()));
  3302. #endif
  3303. #if HAS_TEMP_COOLER
  3304. print_heater_state(H_COOLER, degCooler(), TERN0(HAS_COOLER, degTargetCooler()) OPTARG(SHOW_TEMP_ADC_VALUES, rawCoolerTemp()));
  3305. #endif
  3306. #if HAS_TEMP_PROBE
  3307. print_heater_state(H_PROBE, degProbe(), 0 OPTARG(SHOW_TEMP_ADC_VALUES, rawProbeTemp()));
  3308. #endif
  3309. #if HAS_TEMP_BOARD
  3310. print_heater_state(H_BOARD, degBoard(), 0 OPTARG(SHOW_TEMP_ADC_VALUES, rawBoardTemp()));
  3311. #endif
  3312. #if HAS_TEMP_REDUNDANT
  3313. if (include_r) print_heater_state(H_REDUNDANT, degRedundant(), degRedundantTarget() OPTARG(SHOW_TEMP_ADC_VALUES, rawRedundantTemp()));
  3314. #endif
  3315. #if HAS_MULTI_HOTEND
  3316. HOTEND_LOOP() print_heater_state((heater_id_t)e, degHotend(e), degTargetHotend(e) OPTARG(SHOW_TEMP_ADC_VALUES, rawHotendTemp(e)));
  3317. #endif
  3318. SERIAL_ECHOPGM(" @:", getHeaterPower((heater_id_t)target_extruder));
  3319. #if HAS_HEATED_BED
  3320. SERIAL_ECHOPGM(" B@:", getHeaterPower(H_BED));
  3321. #endif
  3322. #if HAS_HEATED_CHAMBER
  3323. SERIAL_ECHOPGM(" C@:", getHeaterPower(H_CHAMBER));
  3324. #endif
  3325. #if HAS_COOLER
  3326. SERIAL_ECHOPGM(" C@:", getHeaterPower(H_COOLER));
  3327. #endif
  3328. #if HAS_MULTI_HOTEND
  3329. HOTEND_LOOP() {
  3330. SERIAL_ECHOPGM(" @", e);
  3331. SERIAL_CHAR(':');
  3332. SERIAL_ECHO(getHeaterPower((heater_id_t)e));
  3333. }
  3334. #endif
  3335. }
  3336. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  3337. AutoReporter<Temperature::AutoReportTemp> Temperature::auto_reporter;
  3338. void Temperature::AutoReportTemp::report() {
  3339. print_heater_states(active_extruder OPTARG(HAS_TEMP_REDUNDANT, ENABLED(AUTO_REPORT_REDUNDANT)));
  3340. SERIAL_EOL();
  3341. }
  3342. #endif
  3343. #if HAS_HOTEND && HAS_STATUS_MESSAGE
  3344. void Temperature::set_heating_message(const uint8_t e, const bool isM104/*=false*/) {
  3345. const bool heating = isHeatingHotend(e);
  3346. ui.status_printf(0,
  3347. #if HAS_MULTI_HOTEND
  3348. F("E%c " S_FMT), '1' + e
  3349. #else
  3350. F("E1 " S_FMT)
  3351. #endif
  3352. , heating ? GET_TEXT(MSG_HEATING) : GET_TEXT(MSG_COOLING)
  3353. );
  3354. if (isM104) {
  3355. static uint8_t wait_e; wait_e = e;
  3356. ui.set_status_reset_fn([]{
  3357. const celsius_t c = degTargetHotend(wait_e);
  3358. return c < 30 || degHotendNear(wait_e, c);
  3359. });
  3360. }
  3361. }
  3362. #endif
  3363. #if HAS_TEMP_HOTEND
  3364. #ifndef MIN_COOLING_SLOPE_DEG
  3365. #define MIN_COOLING_SLOPE_DEG 1.50
  3366. #endif
  3367. #ifndef MIN_COOLING_SLOPE_TIME
  3368. #define MIN_COOLING_SLOPE_TIME 60
  3369. #endif
  3370. bool Temperature::wait_for_hotend(const uint8_t target_extruder, const bool no_wait_for_cooling/*=true*/
  3371. OPTARG(G26_CLICK_CAN_CANCEL, const bool click_to_cancel/*=false*/)
  3372. ) {
  3373. #if ENABLED(AUTOTEMP)
  3374. REMEMBER(1, planner.autotemp_enabled, false);
  3375. #endif
  3376. #if TEMP_RESIDENCY_TIME > 0
  3377. millis_t residency_start_ms = 0;
  3378. bool first_loop = true;
  3379. // Loop until the temperature has stabilized
  3380. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_RESIDENCY_TIME)))
  3381. #else
  3382. // Loop until the temperature is very close target
  3383. #define TEMP_CONDITIONS (wants_to_cool ? isCoolingHotend(target_extruder) : isHeatingHotend(target_extruder))
  3384. #endif
  3385. #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE)
  3386. KEEPALIVE_STATE(NOT_BUSY);
  3387. #endif
  3388. #if ENABLED(PRINTER_EVENT_LEDS)
  3389. const celsius_float_t start_temp = degHotend(target_extruder);
  3390. printerEventLEDs.onHotendHeatingStart();
  3391. #endif
  3392. bool wants_to_cool = false;
  3393. celsius_float_t target_temp = -1.0, old_temp = 9999.0;
  3394. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  3395. wait_for_heatup = true;
  3396. do {
  3397. // Target temperature might be changed during the loop
  3398. if (target_temp != degTargetHotend(target_extruder)) {
  3399. wants_to_cool = isCoolingHotend(target_extruder);
  3400. target_temp = degTargetHotend(target_extruder);
  3401. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  3402. if (no_wait_for_cooling && wants_to_cool) break;
  3403. }
  3404. now = millis();
  3405. if (ELAPSED(now, next_temp_ms)) { // Print temp & remaining time every 1s while waiting
  3406. next_temp_ms = now + 1000UL;
  3407. print_heater_states(target_extruder);
  3408. #if TEMP_RESIDENCY_TIME > 0
  3409. SERIAL_ECHOPGM(" W:");
  3410. if (residency_start_ms)
  3411. SERIAL_ECHO(long((SEC_TO_MS(TEMP_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL));
  3412. else
  3413. SERIAL_CHAR('?');
  3414. #endif
  3415. SERIAL_EOL();
  3416. }
  3417. idle();
  3418. gcode.reset_stepper_timeout(); // Keep steppers powered
  3419. const celsius_float_t temp = degHotend(target_extruder);
  3420. #if ENABLED(PRINTER_EVENT_LEDS)
  3421. // Gradually change LED strip from violet to red as nozzle heats up
  3422. if (!wants_to_cool) printerEventLEDs.onHotendHeating(start_temp, temp, target_temp);
  3423. #endif
  3424. #if TEMP_RESIDENCY_TIME > 0
  3425. const celsius_float_t temp_diff = ABS(target_temp - temp);
  3426. if (!residency_start_ms) {
  3427. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  3428. if (temp_diff < TEMP_WINDOW)
  3429. residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_RESIDENCY_TIME) / 3 : 0);
  3430. }
  3431. else if (temp_diff > TEMP_HYSTERESIS) {
  3432. // Restart the timer whenever the temperature falls outside the hysteresis.
  3433. residency_start_ms = now;
  3434. }
  3435. first_loop = false;
  3436. #endif
  3437. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  3438. if (wants_to_cool) {
  3439. // Break after MIN_COOLING_SLOPE_TIME seconds
  3440. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  3441. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  3442. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG)) break;
  3443. next_cool_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME);
  3444. old_temp = temp;
  3445. }
  3446. }
  3447. #if G26_CLICK_CAN_CANCEL
  3448. if (click_to_cancel && ui.use_click()) {
  3449. wait_for_heatup = false;
  3450. TERN_(HAS_MARLINUI_MENU, ui.quick_feedback());
  3451. }
  3452. #endif
  3453. } while (wait_for_heatup && TEMP_CONDITIONS);
  3454. if (wait_for_heatup) {
  3455. wait_for_heatup = false;
  3456. #if HAS_DWIN_E3V2_BASIC
  3457. HMI_flag.heat_flag = 0;
  3458. duration_t elapsed = print_job_timer.duration(); // Print timer
  3459. dwin_heat_time = elapsed.value;
  3460. #else
  3461. ui.reset_status();
  3462. #endif
  3463. TERN_(PRINTER_EVENT_LEDS, printerEventLEDs.onHeatingDone());
  3464. return true;
  3465. }
  3466. return false;
  3467. }
  3468. #if ENABLED(WAIT_FOR_HOTEND)
  3469. void Temperature::wait_for_hotend_heating(const uint8_t target_extruder) {
  3470. if (isHeatingHotend(target_extruder)) {
  3471. SERIAL_ECHOLNPGM("Wait for hotend heating...");
  3472. LCD_MESSAGE(MSG_HEATING);
  3473. wait_for_hotend(target_extruder);
  3474. ui.reset_status();
  3475. }
  3476. }
  3477. #endif
  3478. #endif // HAS_TEMP_HOTEND
  3479. #if HAS_HEATED_BED
  3480. #ifndef MIN_COOLING_SLOPE_DEG_BED
  3481. #define MIN_COOLING_SLOPE_DEG_BED 1.00
  3482. #endif
  3483. #ifndef MIN_COOLING_SLOPE_TIME_BED
  3484. #define MIN_COOLING_SLOPE_TIME_BED 60
  3485. #endif
  3486. bool Temperature::wait_for_bed(const bool no_wait_for_cooling/*=true*/
  3487. OPTARG(G26_CLICK_CAN_CANCEL, const bool click_to_cancel/*=false*/)
  3488. ) {
  3489. #if TEMP_BED_RESIDENCY_TIME > 0
  3490. millis_t residency_start_ms = 0;
  3491. bool first_loop = true;
  3492. // Loop until the temperature has stabilized
  3493. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_BED_RESIDENCY_TIME)))
  3494. #else
  3495. // Loop until the temperature is very close target
  3496. #define TEMP_BED_CONDITIONS (wants_to_cool ? isCoolingBed() : isHeatingBed())
  3497. #endif
  3498. #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE)
  3499. KEEPALIVE_STATE(NOT_BUSY);
  3500. #endif
  3501. #if ENABLED(PRINTER_EVENT_LEDS)
  3502. const celsius_float_t start_temp = degBed();
  3503. printerEventLEDs.onBedHeatingStart();
  3504. #endif
  3505. bool wants_to_cool = false;
  3506. celsius_float_t target_temp = -1, old_temp = 9999;
  3507. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  3508. wait_for_heatup = true;
  3509. do {
  3510. // Target temperature might be changed during the loop
  3511. if (target_temp != degTargetBed()) {
  3512. wants_to_cool = isCoolingBed();
  3513. target_temp = degTargetBed();
  3514. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  3515. if (no_wait_for_cooling && wants_to_cool) break;
  3516. }
  3517. now = millis();
  3518. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  3519. next_temp_ms = now + 1000UL;
  3520. print_heater_states(active_extruder);
  3521. #if TEMP_BED_RESIDENCY_TIME > 0
  3522. SERIAL_ECHOPGM(" W:");
  3523. if (residency_start_ms)
  3524. SERIAL_ECHO(long((SEC_TO_MS(TEMP_BED_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL));
  3525. else
  3526. SERIAL_CHAR('?');
  3527. #endif
  3528. SERIAL_EOL();
  3529. }
  3530. idle();
  3531. gcode.reset_stepper_timeout(); // Keep steppers powered
  3532. const celsius_float_t temp = degBed();
  3533. #if ENABLED(PRINTER_EVENT_LEDS)
  3534. // Gradually change LED strip from blue to violet as bed heats up
  3535. if (!wants_to_cool) printerEventLEDs.onBedHeating(start_temp, temp, target_temp);
  3536. #endif
  3537. #if TEMP_BED_RESIDENCY_TIME > 0
  3538. const celsius_float_t temp_diff = ABS(target_temp - temp);
  3539. if (!residency_start_ms) {
  3540. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  3541. if (temp_diff < TEMP_BED_WINDOW)
  3542. residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_BED_RESIDENCY_TIME) / 3 : 0);
  3543. }
  3544. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  3545. // Restart the timer whenever the temperature falls outside the hysteresis.
  3546. residency_start_ms = now;
  3547. }
  3548. #endif // TEMP_BED_RESIDENCY_TIME > 0
  3549. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  3550. if (wants_to_cool) {
  3551. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  3552. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  3553. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  3554. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_BED)) break;
  3555. next_cool_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_BED);
  3556. old_temp = temp;
  3557. }
  3558. }
  3559. #if G26_CLICK_CAN_CANCEL
  3560. if (click_to_cancel && ui.use_click()) {
  3561. wait_for_heatup = false;
  3562. TERN_(HAS_MARLINUI_MENU, ui.quick_feedback());
  3563. }
  3564. #endif
  3565. #if TEMP_BED_RESIDENCY_TIME > 0
  3566. first_loop = false;
  3567. #endif
  3568. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  3569. if (wait_for_heatup) {
  3570. wait_for_heatup = false;
  3571. ui.reset_status();
  3572. return true;
  3573. }
  3574. return false;
  3575. }
  3576. void Temperature::wait_for_bed_heating() {
  3577. if (isHeatingBed()) {
  3578. SERIAL_ECHOLNPGM("Wait for bed heating...");
  3579. LCD_MESSAGE(MSG_BED_HEATING);
  3580. wait_for_bed();
  3581. ui.reset_status();
  3582. }
  3583. }
  3584. #endif // HAS_HEATED_BED
  3585. #if HAS_TEMP_PROBE
  3586. #ifndef MIN_DELTA_SLOPE_DEG_PROBE
  3587. #define MIN_DELTA_SLOPE_DEG_PROBE 1.0
  3588. #endif
  3589. #ifndef MIN_DELTA_SLOPE_TIME_PROBE
  3590. #define MIN_DELTA_SLOPE_TIME_PROBE 600
  3591. #endif
  3592. bool Temperature::wait_for_probe(const celsius_t target_temp, bool no_wait_for_cooling/*=true*/) {
  3593. const bool wants_to_cool = isProbeAboveTemp(target_temp),
  3594. will_wait = !(wants_to_cool && no_wait_for_cooling);
  3595. if (will_wait)
  3596. SERIAL_ECHOLNPGM("Waiting for probe to ", wants_to_cool ? F("cool down") : F("heat up"), " to ", target_temp, " degrees.");
  3597. #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE)
  3598. KEEPALIVE_STATE(NOT_BUSY);
  3599. #endif
  3600. float old_temp = 9999;
  3601. millis_t next_temp_ms = 0, next_delta_check_ms = 0;
  3602. wait_for_heatup = true;
  3603. while (will_wait && wait_for_heatup) {
  3604. // Print Temp Reading every 10 seconds while heating up.
  3605. millis_t now = millis();
  3606. if (!next_temp_ms || ELAPSED(now, next_temp_ms)) {
  3607. next_temp_ms = now + 10000UL;
  3608. print_heater_states(active_extruder);
  3609. SERIAL_EOL();
  3610. }
  3611. idle();
  3612. gcode.reset_stepper_timeout(); // Keep steppers powered
  3613. // Break after MIN_DELTA_SLOPE_TIME_PROBE seconds if the temperature
  3614. // did not drop at least MIN_DELTA_SLOPE_DEG_PROBE. This avoids waiting
  3615. // forever as the probe is not actively heated.
  3616. if (!next_delta_check_ms || ELAPSED(now, next_delta_check_ms)) {
  3617. const float temp = degProbe(),
  3618. delta_temp = old_temp > temp ? old_temp - temp : temp - old_temp;
  3619. if (delta_temp < float(MIN_DELTA_SLOPE_DEG_PROBE)) {
  3620. SERIAL_ECHOLNPGM("Timed out waiting for probe temperature.");
  3621. break;
  3622. }
  3623. next_delta_check_ms = now + SEC_TO_MS(MIN_DELTA_SLOPE_TIME_PROBE);
  3624. old_temp = temp;
  3625. }
  3626. // Loop until the temperature is very close target
  3627. if (!(wants_to_cool ? isProbeAboveTemp(target_temp) : isProbeBelowTemp(target_temp))) {
  3628. SERIAL_ECHOLN(wants_to_cool ? PSTR("Cooldown") : PSTR("Heatup"));
  3629. SERIAL_ECHOLNPGM(" complete, target probe temperature reached.");
  3630. break;
  3631. }
  3632. }
  3633. if (wait_for_heatup) {
  3634. wait_for_heatup = false;
  3635. ui.reset_status();
  3636. return true;
  3637. }
  3638. else if (will_wait)
  3639. SERIAL_ECHOLNPGM("Canceled wait for probe temperature.");
  3640. return false;
  3641. }
  3642. #endif // HAS_TEMP_PROBE
  3643. #if HAS_HEATED_CHAMBER
  3644. #ifndef MIN_COOLING_SLOPE_DEG_CHAMBER
  3645. #define MIN_COOLING_SLOPE_DEG_CHAMBER 1.50
  3646. #endif
  3647. #ifndef MIN_COOLING_SLOPE_TIME_CHAMBER
  3648. #define MIN_COOLING_SLOPE_TIME_CHAMBER 120
  3649. #endif
  3650. bool Temperature::wait_for_chamber(const bool no_wait_for_cooling/*=true*/) {
  3651. #if TEMP_CHAMBER_RESIDENCY_TIME > 0
  3652. millis_t residency_start_ms = 0;
  3653. bool first_loop = true;
  3654. // Loop until the temperature has stabilized
  3655. #define TEMP_CHAMBER_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_CHAMBER_RESIDENCY_TIME)))
  3656. #else
  3657. // Loop until the temperature is very close target
  3658. #define TEMP_CHAMBER_CONDITIONS (wants_to_cool ? isCoolingChamber() : isHeatingChamber())
  3659. #endif
  3660. #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE)
  3661. KEEPALIVE_STATE(NOT_BUSY);
  3662. #endif
  3663. bool wants_to_cool = false;
  3664. float target_temp = -1, old_temp = 9999;
  3665. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  3666. wait_for_heatup = true;
  3667. do {
  3668. // Target temperature might be changed during the loop
  3669. if (target_temp != degTargetChamber()) {
  3670. wants_to_cool = isCoolingChamber();
  3671. target_temp = degTargetChamber();
  3672. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  3673. if (no_wait_for_cooling && wants_to_cool) break;
  3674. }
  3675. now = millis();
  3676. if (ELAPSED(now, next_temp_ms)) { // Print Temp Reading every 1 second while heating up.
  3677. next_temp_ms = now + 1000UL;
  3678. print_heater_states(active_extruder);
  3679. #if TEMP_CHAMBER_RESIDENCY_TIME > 0
  3680. SERIAL_ECHOPGM(" W:");
  3681. if (residency_start_ms)
  3682. SERIAL_ECHO(long((SEC_TO_MS(TEMP_CHAMBER_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL));
  3683. else
  3684. SERIAL_CHAR('?');
  3685. #endif
  3686. SERIAL_EOL();
  3687. }
  3688. idle();
  3689. gcode.reset_stepper_timeout(); // Keep steppers powered
  3690. const float temp = degChamber();
  3691. #if TEMP_CHAMBER_RESIDENCY_TIME > 0
  3692. const float temp_diff = ABS(target_temp - temp);
  3693. if (!residency_start_ms) {
  3694. // Start the TEMP_CHAMBER_RESIDENCY_TIME timer when we reach target temp for the first time.
  3695. if (temp_diff < TEMP_CHAMBER_WINDOW)
  3696. residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_CHAMBER_RESIDENCY_TIME) / 3 : 0);
  3697. }
  3698. else if (temp_diff > TEMP_CHAMBER_HYSTERESIS) {
  3699. // Restart the timer whenever the temperature falls outside the hysteresis.
  3700. residency_start_ms = now;
  3701. }
  3702. first_loop = false;
  3703. #endif // TEMP_CHAMBER_RESIDENCY_TIME > 0
  3704. // Prevent a wait-forever situation if R is misused i.e. M191 R0
  3705. if (wants_to_cool) {
  3706. // Break after MIN_COOLING_SLOPE_TIME_CHAMBER seconds
  3707. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_CHAMBER
  3708. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  3709. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_CHAMBER)) break;
  3710. next_cool_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_CHAMBER);
  3711. old_temp = temp;
  3712. }
  3713. }
  3714. } while (wait_for_heatup && TEMP_CHAMBER_CONDITIONS);
  3715. if (wait_for_heatup) {
  3716. wait_for_heatup = false;
  3717. ui.reset_status();
  3718. return true;
  3719. }
  3720. return false;
  3721. }
  3722. #endif // HAS_HEATED_CHAMBER
  3723. #if HAS_COOLER
  3724. #ifndef MIN_COOLING_SLOPE_DEG_COOLER
  3725. #define MIN_COOLING_SLOPE_DEG_COOLER 1.50
  3726. #endif
  3727. #ifndef MIN_COOLING_SLOPE_TIME_COOLER
  3728. #define MIN_COOLING_SLOPE_TIME_COOLER 120
  3729. #endif
  3730. bool Temperature::wait_for_cooler(const bool no_wait_for_cooling/*=true*/) {
  3731. #if TEMP_COOLER_RESIDENCY_TIME > 0
  3732. millis_t residency_start_ms = 0;
  3733. bool first_loop = true;
  3734. // Loop until the temperature has stabilized
  3735. #define TEMP_COOLER_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_COOLER_RESIDENCY_TIME)))
  3736. #else
  3737. // Loop until the temperature is very close target
  3738. #define TEMP_COOLER_CONDITIONS (wants_to_cool ? isLaserHeating() : isLaserCooling())
  3739. #endif
  3740. #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE)
  3741. KEEPALIVE_STATE(NOT_BUSY);
  3742. #endif
  3743. bool wants_to_cool = false;
  3744. float target_temp = -1, previous_temp = 9999;
  3745. millis_t now, next_temp_ms = 0, next_cooling_check_ms = 0;
  3746. wait_for_heatup = true;
  3747. do {
  3748. // Target temperature might be changed during the loop
  3749. if (target_temp != degTargetCooler()) {
  3750. wants_to_cool = isLaserHeating();
  3751. target_temp = degTargetCooler();
  3752. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  3753. if (no_wait_for_cooling && wants_to_cool) break;
  3754. }
  3755. now = millis();
  3756. if (ELAPSED(now, next_temp_ms)) { // Print Temp Reading every 1 second while heating up.
  3757. next_temp_ms = now + 1000UL;
  3758. print_heater_states(active_extruder);
  3759. #if TEMP_COOLER_RESIDENCY_TIME > 0
  3760. SERIAL_ECHOPGM(" W:");
  3761. if (residency_start_ms)
  3762. SERIAL_ECHO(long((SEC_TO_MS(TEMP_COOLER_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL));
  3763. else
  3764. SERIAL_CHAR('?');
  3765. #endif
  3766. SERIAL_EOL();
  3767. }
  3768. idle();
  3769. gcode.reset_stepper_timeout(); // Keep steppers powered
  3770. const celsius_float_t current_temp = degCooler();
  3771. #if TEMP_COOLER_RESIDENCY_TIME > 0
  3772. const celsius_float_t temp_diff = ABS(target_temp - temp);
  3773. if (!residency_start_ms) {
  3774. // Start the TEMP_COOLER_RESIDENCY_TIME timer when we reach target temp for the first time.
  3775. if (temp_diff < TEMP_COOLER_WINDOW)
  3776. residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_COOLER_RESIDENCY_TIME) / 3 : 0);
  3777. }
  3778. else if (temp_diff > TEMP_COOLER_HYSTERESIS) {
  3779. // Restart the timer whenever the temperature falls outside the hysteresis.
  3780. residency_start_ms = now;
  3781. }
  3782. first_loop = false;
  3783. #endif // TEMP_COOLER_RESIDENCY_TIME > 0
  3784. if (wants_to_cool) {
  3785. // Break after MIN_COOLING_SLOPE_TIME_CHAMBER seconds
  3786. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_CHAMBER
  3787. if (!next_cooling_check_ms || ELAPSED(now, next_cooling_check_ms)) {
  3788. if (previous_temp - current_temp < float(MIN_COOLING_SLOPE_DEG_COOLER)) break;
  3789. next_cooling_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_COOLER);
  3790. previous_temp = current_temp;
  3791. }
  3792. }
  3793. } while (wait_for_heatup && TEMP_COOLER_CONDITIONS);
  3794. // Prevent a wait-forever situation if R is misused i.e. M191 R0
  3795. if (wait_for_heatup) {
  3796. wait_for_heatup = false;
  3797. ui.reset_status();
  3798. return true;
  3799. }
  3800. return false;
  3801. }
  3802. #endif // HAS_COOLER
  3803. #endif // HAS_TEMP_SENSOR