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

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