temperature.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965
  1. /*
  2. temperature.c - temperature control
  3. Part of Marlin
  4. Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /*
  17. This firmware is a mashup between Sprinter and grbl.
  18. (https://github.com/kliment/Sprinter)
  19. (https://github.com/simen/grbl/tree)
  20. It has preliminary support for Matthew Roberts advance algorithm
  21. http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  22. */
  23. #include "temperature.h"
  24. #include "stepper.h"
  25. #include "ultralcd.h"
  26. #include "menu.h"
  27. #include "sound.h"
  28. #include "fancheck.h"
  29. #include "messages.h"
  30. #include "language.h"
  31. #include "SdFatUtil.h"
  32. #include <avr/wdt.h>
  33. #include <util/atomic.h>
  34. #include "adc.h"
  35. #include "ConfigurationStore.h"
  36. #include "Timer.h"
  37. #include "Configuration_var.h"
  38. #include "Prusa_farm.h"
  39. #if (ADC_OVRSAMPL != OVERSAMPLENR)
  40. #error "ADC_OVRSAMPL oversampling must match OVERSAMPLENR"
  41. #endif
  42. #ifdef SYSTEM_TIMER_2
  43. #define ENABLE_SOFT_PWM_INTERRUPT() TIMSK2 |= (1<<OCIE2B)
  44. #define DISABLE_SOFT_PWM_INTERRUPT() TIMSK2 &= ~(1<<OCIE2B)
  45. #else //SYSTEM_TIMER_2
  46. #define ENABLE_SOFT_PWM_INTERRUPT() TIMSK0 |= (1<<OCIE0B)
  47. #define DISABLE_SOFT_PWM_INTERRUPT() TIMSK0 &= ~(1<<OCIE0B)
  48. #endif //SYSTEM_TIMER_2
  49. // temperature manager timer configuration
  50. #define TEMP_MGR_INTV 0.27 // seconds, ~3.7Hz
  51. #define TEMP_TIM_PRESCALE 256
  52. #define TEMP_TIM_OCRA_OVF (uint16_t)(TEMP_MGR_INTV / ((long double)TEMP_TIM_PRESCALE / F_CPU))
  53. #define TEMP_TIM_REGNAME(registerbase,number,suffix) _REGNAME(registerbase,number,suffix)
  54. #undef B0 //Necessary hack because of "binary.h" included in "Arduino.h" included in "system_timer.h" included in this file...
  55. #define TCCRxA TEMP_TIM_REGNAME(TCCR, TEMP_TIM, A)
  56. #define TCCRxB TEMP_TIM_REGNAME(TCCR, TEMP_TIM, B)
  57. #define TCCRxC TEMP_TIM_REGNAME(TCCR, TEMP_TIM, C)
  58. #define TCNTx TEMP_TIM_REGNAME(TCNT, TEMP_TIM,)
  59. #define OCRxA TEMP_TIM_REGNAME(OCR, TEMP_TIM, A)
  60. #define TIMSKx TEMP_TIM_REGNAME(TIMSK, TEMP_TIM,)
  61. #define TIFRx TEMP_TIM_REGNAME(TIFR, TEMP_TIM,)
  62. #define TIMERx_COMPA_vect TEMP_TIM_REGNAME(TIMER, TEMP_TIM, _COMPA_vect)
  63. #define CSx0 TEMP_TIM_REGNAME(CS, TEMP_TIM, 0)
  64. #define CSx1 TEMP_TIM_REGNAME(CS, TEMP_TIM, 1)
  65. #define CSx2 TEMP_TIM_REGNAME(CS, TEMP_TIM, 2)
  66. #define WGMx0 TEMP_TIM_REGNAME(WGM, TEMP_TIM, 0)
  67. #define WGMx1 TEMP_TIM_REGNAME(WGM, TEMP_TIM, 1)
  68. #define WGMx2 TEMP_TIM_REGNAME(WGM, TEMP_TIM, 2)
  69. #define WGMx3 TEMP_TIM_REGNAME(WGM, TEMP_TIM, 3)
  70. #define COMxA0 TEMP_TIM_REGNAME(COM, TEMP_TIM, A0)
  71. #define COMxB0 TEMP_TIM_REGNAME(COM, TEMP_TIM, B0)
  72. #define COMxC0 TEMP_TIM_REGNAME(COM, TEMP_TIM, C0)
  73. #define OCIExA TEMP_TIM_REGNAME(OCIE, TEMP_TIM, A)
  74. #define OCFxA TEMP_TIM_REGNAME(OCF, TEMP_TIM, A)
  75. #define TEMP_MGR_INT_FLAG_STATE() (TIFRx & (1<<OCFxA))
  76. #define TEMP_MGR_INT_FLAG_CLEAR() TIFRx |= (1<<OCFxA)
  77. #define TEMP_MGR_INTERRUPT_STATE() (TIMSKx & (1<<OCIExA))
  78. #define ENABLE_TEMP_MGR_INTERRUPT() TIMSKx |= (1<<OCIExA)
  79. #define DISABLE_TEMP_MGR_INTERRUPT() TIMSKx &= ~(1<<OCIExA)
  80. #ifdef TEMP_MODEL
  81. // temperature model interface
  82. #include "temp_model.h"
  83. #endif
  84. #include "Filament_sensor.h"
  85. //===========================================================================
  86. //=============================public variables============================
  87. //===========================================================================
  88. int target_temperature[EXTRUDERS] = { 0 };
  89. int target_temperature_bed = 0;
  90. int current_temperature_raw[EXTRUDERS] = { 0 };
  91. float current_temperature[EXTRUDERS] = { 0.0 };
  92. #ifdef PINDA_THERMISTOR
  93. uint16_t current_temperature_raw_pinda = 0;
  94. float current_temperature_pinda = 0.0;
  95. #endif //PINDA_THERMISTOR
  96. #ifdef AMBIENT_THERMISTOR
  97. int current_temperature_raw_ambient = 0;
  98. float current_temperature_ambient = 0.0;
  99. #endif //AMBIENT_THERMISTOR
  100. #ifdef VOLT_PWR_PIN
  101. int current_voltage_raw_pwr = 0;
  102. #endif
  103. #ifdef VOLT_BED_PIN
  104. int current_voltage_raw_bed = 0;
  105. #endif
  106. int current_temperature_bed_raw = 0;
  107. float current_temperature_bed = 0.0;
  108. #ifdef PIDTEMP
  109. float _Kp, _Ki, _Kd;
  110. int pid_cycle, pid_number_of_cycles;
  111. static bool pid_tuning_finished = true;
  112. bool pidTuningRunning() {
  113. return !pid_tuning_finished;
  114. }
  115. void preparePidTuning() {
  116. // ensure heaters are disabled before we switch off PID management!
  117. disable_heater();
  118. pid_tuning_finished = false;
  119. }
  120. #endif //PIDTEMP
  121. unsigned char soft_pwm_bed;
  122. #ifdef BABYSTEPPING
  123. volatile int babystepsTodo[3]={0,0,0};
  124. #endif
  125. //===========================================================================
  126. //=============================private variables============================
  127. //===========================================================================
  128. static volatile bool temp_meas_ready = false;
  129. #ifdef PIDTEMP
  130. //static cannot be external:
  131. static float iState_sum[EXTRUDERS] = { 0 };
  132. static float dState_last[EXTRUDERS] = { 0 };
  133. static float pTerm[EXTRUDERS];
  134. static float iTerm[EXTRUDERS];
  135. static float dTerm[EXTRUDERS];
  136. static float pid_error[EXTRUDERS];
  137. static float iState_sum_min[EXTRUDERS];
  138. static float iState_sum_max[EXTRUDERS];
  139. static bool pid_reset[EXTRUDERS];
  140. #endif //PIDTEMP
  141. #ifdef PIDTEMPBED
  142. //static cannot be external:
  143. static float temp_iState_bed = { 0 };
  144. static float temp_dState_bed = { 0 };
  145. static float pTerm_bed;
  146. static float iTerm_bed;
  147. static float dTerm_bed;
  148. static float pid_error_bed;
  149. static float temp_iState_min_bed;
  150. static float temp_iState_max_bed;
  151. #else //PIDTEMPBED
  152. static unsigned long previous_millis_bed_heater;
  153. #endif //PIDTEMPBED
  154. static unsigned char soft_pwm[EXTRUDERS];
  155. #ifdef FAN_SOFT_PWM
  156. unsigned char fanSpeedSoftPwm;
  157. static unsigned char soft_pwm_fan;
  158. #endif
  159. uint8_t fanSpeedBckp = 255;
  160. #if EXTRUDERS > 3
  161. # error Unsupported number of extruders
  162. #elif EXTRUDERS > 2
  163. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1, v2, v3 }
  164. #elif EXTRUDERS > 1
  165. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1, v2 }
  166. #else
  167. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1 }
  168. #endif
  169. // Init min and max temp with extreme values to prevent false errors during startup
  170. static int minttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP );
  171. static int maxttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP );
  172. static int minttemp[EXTRUDERS] = ARRAY_BY_EXTRUDERS( 0, 0, 0 );
  173. static int maxttemp[EXTRUDERS] = ARRAY_BY_EXTRUDERS( 16383, 16383, 16383 );
  174. #ifdef BED_MINTEMP
  175. static int bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
  176. #endif
  177. #ifdef BED_MAXTEMP
  178. static int bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
  179. #endif
  180. #ifdef AMBIENT_MINTEMP
  181. static int ambient_minttemp_raw = AMBIENT_RAW_LO_TEMP;
  182. #endif
  183. #ifdef AMBIENT_MAXTEMP
  184. static int ambient_maxttemp_raw = AMBIENT_RAW_HI_TEMP;
  185. #endif
  186. static void *heater_ttbl_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS( (void *)HEATER_0_TEMPTABLE, (void *)HEATER_1_TEMPTABLE, (void *)HEATER_2_TEMPTABLE );
  187. static uint8_t heater_ttbllen_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN );
  188. static float analog2temp(int raw, uint8_t e);
  189. static float analog2tempBed(int raw);
  190. #ifdef AMBIENT_MAXTEMP
  191. static float analog2tempAmbient(int raw);
  192. #endif
  193. static void updateTemperatures();
  194. enum TempRunawayStates : uint8_t
  195. {
  196. TempRunaway_INACTIVE = 0,
  197. TempRunaway_PREHEAT = 1,
  198. TempRunaway_ACTIVE = 2,
  199. };
  200. #ifndef SOFT_PWM_SCALE
  201. #define SOFT_PWM_SCALE 0
  202. #endif
  203. //===========================================================================
  204. //============================= functions ============================
  205. //===========================================================================
  206. #if (defined (TEMP_RUNAWAY_BED_HYSTERESIS) && TEMP_RUNAWAY_BED_TIMEOUT > 0) || (defined (TEMP_RUNAWAY_EXTRUDER_HYSTERESIS) && TEMP_RUNAWAY_EXTRUDER_TIMEOUT > 0)
  207. static uint8_t temp_runaway_status[1 + EXTRUDERS];
  208. static float temp_runaway_target[1 + EXTRUDERS];
  209. static uint32_t temp_runaway_timer[1 + EXTRUDERS];
  210. static uint16_t temp_runaway_error_counter[1 + EXTRUDERS];
  211. static void temp_runaway_check(uint8_t _heater_id, float _target_temperature, float _current_temperature, float _output, bool _isbed);
  212. static void temp_runaway_stop(bool isPreheat, bool isBed);
  213. #endif
  214. // return "false", if all extruder-heaters are 'off' (ie. "true", if any heater is 'on')
  215. bool checkAllHotends(void)
  216. {
  217. bool result=false;
  218. for(int i=0;i<EXTRUDERS;i++) result=(result||(target_temperature[i]!=0));
  219. return(result);
  220. }
  221. // WARNING: the following function has been marked noinline to avoid a GCC 4.9.2 LTO
  222. // codegen bug causing a stack overwrite issue in process_commands()
  223. void __attribute__((noinline)) PID_autotune(float temp, int extruder, int ncycles)
  224. {
  225. preparePidTuning();
  226. pid_number_of_cycles = ncycles;
  227. float input = 0.0;
  228. pid_cycle=0;
  229. bool heating = true;
  230. unsigned long temp_millis = _millis();
  231. unsigned long t1=temp_millis;
  232. unsigned long t2=temp_millis;
  233. long t_high = 0;
  234. long t_low = 0;
  235. long bias, d;
  236. float Ku, Tu;
  237. float max = 0, min = 10000;
  238. uint8_t safety_check_cycles = 0;
  239. const uint8_t safety_check_cycles_count = (extruder < 0) ? 45 : 10; //10 cycles / 20s delay for extruder and 45 cycles / 90s for heatbed
  240. float temp_ambient;
  241. #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1)
  242. unsigned long extruder_autofan_last_check = _millis();
  243. #endif
  244. if ((extruder >= EXTRUDERS)
  245. #if (TEMP_BED_PIN <= -1)
  246. ||(extruder < 0)
  247. #endif
  248. ){
  249. SERIAL_ECHOLNPGM("PID Autotune failed. Bad extruder number.");
  250. pid_tuning_finished = true;
  251. pid_cycle = 0;
  252. return;
  253. }
  254. SERIAL_ECHOLNPGM("PID Autotune start");
  255. if (extruder<0)
  256. {
  257. soft_pwm_bed = (MAX_BED_POWER)/2;
  258. timer02_set_pwm0(soft_pwm_bed << 1);
  259. bias = d = (MAX_BED_POWER)/2;
  260. target_temperature_bed = (int)temp; // to display the requested target bed temperature properly on the main screen
  261. }
  262. else
  263. {
  264. soft_pwm[extruder] = (PID_MAX)/2;
  265. bias = d = (PID_MAX)/2;
  266. target_temperature[extruder] = (int)temp; // to display the requested target extruder temperature properly on the main screen
  267. }
  268. for(;;) {
  269. #ifdef WATCHDOG
  270. wdt_reset();
  271. #endif //WATCHDOG
  272. if(temp_meas_ready == true) { // temp sample ready
  273. updateTemperatures();
  274. input = (extruder<0)?current_temperature_bed:current_temperature[extruder];
  275. max=max(max,input);
  276. min=min(min,input);
  277. #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1)
  278. if(_millis() - extruder_autofan_last_check > 2500) {
  279. checkExtruderAutoFans();
  280. extruder_autofan_last_check = _millis();
  281. }
  282. #endif
  283. if(heating == true && input > temp) {
  284. if(_millis() - t2 > 5000) {
  285. heating=false;
  286. if (extruder<0)
  287. {
  288. soft_pwm_bed = (bias - d) >> 1;
  289. timer02_set_pwm0(soft_pwm_bed << 1);
  290. }
  291. else
  292. soft_pwm[extruder] = (bias - d) >> 1;
  293. t1=_millis();
  294. t_high=t1 - t2;
  295. max=temp;
  296. }
  297. }
  298. if(heating == false && input < temp) {
  299. if(_millis() - t1 > 5000) {
  300. heating=true;
  301. t2=_millis();
  302. t_low=t2 - t1;
  303. if(pid_cycle > 0) {
  304. bias += (d*(t_high - t_low))/(t_low + t_high);
  305. bias = constrain(bias, 20 ,(extruder<0?(MAX_BED_POWER):(PID_MAX))-20);
  306. if(bias > (extruder<0?(MAX_BED_POWER):(PID_MAX))/2) d = (extruder<0?(MAX_BED_POWER):(PID_MAX)) - 1 - bias;
  307. else d = bias;
  308. SERIAL_PROTOCOLPGM(" bias: "); SERIAL_PROTOCOL(bias);
  309. SERIAL_PROTOCOLPGM(" d: "); SERIAL_PROTOCOL(d);
  310. SERIAL_PROTOCOLPGM(" min: "); SERIAL_PROTOCOL(min);
  311. SERIAL_PROTOCOLPGM(" max: "); SERIAL_PROTOCOLLN(max);
  312. if(pid_cycle > 2) {
  313. Ku = (4.0*d)/(3.14159*(max-min)/2.0);
  314. Tu = ((float)(t_low + t_high)/1000.0);
  315. SERIAL_PROTOCOLPGM(" Ku: "); SERIAL_PROTOCOL(Ku);
  316. SERIAL_PROTOCOLPGM(" Tu: "); SERIAL_PROTOCOLLN(Tu);
  317. _Kp = 0.6*Ku;
  318. _Ki = 2*_Kp/Tu;
  319. _Kd = _Kp*Tu/8;
  320. SERIAL_PROTOCOLLNPGM(" Classic PID ");
  321. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  322. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  323. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  324. /*
  325. _Kp = 0.33*Ku;
  326. _Ki = _Kp/Tu;
  327. _Kd = _Kp*Tu/3;
  328. SERIAL_PROTOCOLLNPGM(" Some overshoot ");
  329. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  330. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  331. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  332. _Kp = 0.2*Ku;
  333. _Ki = 2*_Kp/Tu;
  334. _Kd = _Kp*Tu/3;
  335. SERIAL_PROTOCOLLNPGM(" No overshoot ");
  336. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  337. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  338. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  339. */
  340. }
  341. }
  342. if (extruder<0)
  343. {
  344. soft_pwm_bed = (bias + d) >> 1;
  345. timer02_set_pwm0(soft_pwm_bed << 1);
  346. }
  347. else
  348. soft_pwm[extruder] = (bias + d) >> 1;
  349. pid_cycle++;
  350. min=temp;
  351. }
  352. }
  353. }
  354. if(input > (temp + 20)) {
  355. SERIAL_PROTOCOLLNPGM("PID Autotune failed! Temperature too high");
  356. pid_tuning_finished = true;
  357. pid_cycle = 0;
  358. return;
  359. }
  360. if(_millis() - temp_millis > 2000) {
  361. int p;
  362. if (extruder<0){
  363. p=soft_pwm_bed;
  364. SERIAL_PROTOCOLPGM("B:");
  365. }else{
  366. p=soft_pwm[extruder];
  367. SERIAL_PROTOCOLPGM("T:");
  368. }
  369. SERIAL_PROTOCOL(input);
  370. SERIAL_PROTOCOLPGM(" @:");
  371. SERIAL_PROTOCOLLN(p);
  372. if (safety_check_cycles == 0) { //save ambient temp
  373. temp_ambient = input;
  374. //SERIAL_ECHOPGM("Ambient T: ");
  375. //MYSERIAL.println(temp_ambient);
  376. safety_check_cycles++;
  377. }
  378. else if (safety_check_cycles < safety_check_cycles_count) { //delay
  379. safety_check_cycles++;
  380. }
  381. else if (safety_check_cycles == safety_check_cycles_count){ //check that temperature is rising
  382. safety_check_cycles++;
  383. //SERIAL_ECHOPGM("Time from beginning: ");
  384. //MYSERIAL.print(safety_check_cycles_count * 2);
  385. //SERIAL_ECHOPGM("s. Difference between current and ambient T: ");
  386. //MYSERIAL.println(input - temp_ambient);
  387. if (fabs(input - temp_ambient) < 5.0) {
  388. temp_runaway_stop(false, (extruder<0));
  389. pid_tuning_finished = true;
  390. return;
  391. }
  392. }
  393. temp_millis = _millis();
  394. }
  395. if(((_millis() - t1) + (_millis() - t2)) > (10L*60L*1000L*2L)) {
  396. SERIAL_PROTOCOLLNPGM("PID Autotune failed! timeout");
  397. pid_tuning_finished = true;
  398. pid_cycle = 0;
  399. return;
  400. }
  401. if(pid_cycle > ncycles) {
  402. SERIAL_PROTOCOLLNPGM("PID Autotune finished! Put the last Kp, Ki and Kd constants from above into Configuration.h");
  403. pid_tuning_finished = true;
  404. pid_cycle = 0;
  405. return;
  406. }
  407. lcd_update(0);
  408. }
  409. }
  410. void updatePID()
  411. {
  412. // TODO: iState_sum_max and PID values should be synchronized for temp_mgr_isr
  413. #ifdef PIDTEMP
  414. for(uint_least8_t e = 0; e < EXTRUDERS; e++) {
  415. iState_sum_max[e] = PID_INTEGRAL_DRIVE_MAX / cs.Ki;
  416. }
  417. #endif
  418. #ifdef PIDTEMPBED
  419. temp_iState_max_bed = PID_INTEGRAL_DRIVE_MAX / cs.bedKi;
  420. #endif
  421. }
  422. int getHeaterPower(int heater) {
  423. if (heater<0)
  424. return soft_pwm_bed;
  425. return soft_pwm[heater];
  426. }
  427. // reset PID state after changing target_temperature
  428. void resetPID(uint8_t extruder _UNUSED) {}
  429. enum class TempErrorSource : uint8_t
  430. {
  431. hotend,
  432. bed,
  433. #ifdef AMBIENT_THERMISTOR
  434. ambient,
  435. #endif
  436. };
  437. // thermal error type (in order of decreasing priority!)
  438. enum class TempErrorType : uint8_t
  439. {
  440. max,
  441. min,
  442. preheat,
  443. runaway,
  444. #ifdef TEMP_MODEL
  445. model,
  446. #endif
  447. };
  448. // error state (updated via set_temp_error from isr context)
  449. volatile static union
  450. {
  451. uint8_t v;
  452. struct
  453. {
  454. uint8_t error: 1; // error condition
  455. uint8_t assert: 1; // error is still asserted
  456. uint8_t source: 2; // source
  457. uint8_t index: 1; // source index
  458. uint8_t type: 3; // error type
  459. };
  460. } temp_error_state;
  461. // set the error type from within the temp_mgr isr to be handled in manager_heater
  462. // - immediately disable all heaters and turn on all fans at full speed
  463. // - prevent the user to set temperatures until all errors are cleared
  464. void set_temp_error(TempErrorSource source, uint8_t index, TempErrorType type)
  465. {
  466. // save the original target temperatures for recovery before disabling heaters
  467. if(!temp_error_state.error && !saved_printing) {
  468. saved_bed_temperature = target_temperature_bed;
  469. saved_extruder_temperature = target_temperature[index];
  470. saved_fan_speed = fanSpeed;
  471. }
  472. // keep disabling heaters and keep fans on as long as the condition is asserted
  473. disable_heater();
  474. hotendFanSetFullSpeed();
  475. // set the initial error source to the highest priority error
  476. if(!temp_error_state.error || (uint8_t)type < temp_error_state.type) {
  477. temp_error_state.source = (uint8_t)source;
  478. temp_error_state.index = index;
  479. temp_error_state.type = (uint8_t)type;
  480. }
  481. // always set the error state
  482. temp_error_state.error = true;
  483. temp_error_state.assert = true;
  484. }
  485. bool get_temp_error()
  486. {
  487. return temp_error_state.v;
  488. }
  489. void handle_temp_error();
  490. void manage_heater()
  491. {
  492. #ifdef WATCHDOG
  493. wdt_reset();
  494. #endif //WATCHDOG
  495. // limit execution to the same rate as temp_mgr (low-level fault handling is already handled -
  496. // any remaining error handling is just user-facing and can wait one extra cycle)
  497. if(!temp_meas_ready)
  498. return;
  499. // syncronize temperatures with isr
  500. updateTemperatures();
  501. #ifdef TEMP_MODEL
  502. // handle model warnings first, so not to override the error handler
  503. if(temp_model::warning_state.warning)
  504. temp_model::handle_warning();
  505. #endif
  506. // handle temperature errors
  507. if(temp_error_state.v)
  508. handle_temp_error();
  509. // periodically check fans
  510. checkFans();
  511. #ifdef TEMP_MODEL_DEBUG
  512. temp_model::log_usr();
  513. #endif
  514. }
  515. #define PGM_RD_W(x) (short)pgm_read_word(&x)
  516. // Derived from RepRap FiveD extruder::getTemperature()
  517. // For hot end temperature measurement.
  518. static float analog2temp(int raw, uint8_t e) {
  519. if(e >= EXTRUDERS)
  520. {
  521. SERIAL_ERROR_START;
  522. SERIAL_ERROR((int)e);
  523. SERIAL_ERRORLNPGM(" - Invalid extruder number !");
  524. kill(NULL, 6);
  525. return 0.0;
  526. }
  527. #ifdef HEATER_0_USES_MAX6675
  528. if (e == 0)
  529. {
  530. return 0.25 * raw;
  531. }
  532. #endif
  533. if(heater_ttbl_map[e] != NULL)
  534. {
  535. float celsius = 0;
  536. uint8_t i;
  537. short (*tt)[][2] = (short (*)[][2])(heater_ttbl_map[e]);
  538. for (i=1; i<heater_ttbllen_map[e]; i++)
  539. {
  540. if (PGM_RD_W((*tt)[i][0]) > raw)
  541. {
  542. celsius = PGM_RD_W((*tt)[i-1][1]) +
  543. (raw - PGM_RD_W((*tt)[i-1][0])) *
  544. (float)(PGM_RD_W((*tt)[i][1]) - PGM_RD_W((*tt)[i-1][1])) /
  545. (float)(PGM_RD_W((*tt)[i][0]) - PGM_RD_W((*tt)[i-1][0]));
  546. break;
  547. }
  548. }
  549. // Overflow: Set to last value in the table
  550. if (i == heater_ttbllen_map[e]) celsius = PGM_RD_W((*tt)[i-1][1]);
  551. return celsius;
  552. }
  553. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET;
  554. }
  555. // Derived from RepRap FiveD extruder::getTemperature()
  556. // For bed temperature measurement.
  557. static float analog2tempBed(int raw) {
  558. #ifdef BED_USES_THERMISTOR
  559. float celsius = 0;
  560. byte i;
  561. for (i=1; i<BEDTEMPTABLE_LEN; i++)
  562. {
  563. if (PGM_RD_W(BEDTEMPTABLE[i][0]) > raw)
  564. {
  565. celsius = PGM_RD_W(BEDTEMPTABLE[i-1][1]) +
  566. (raw - PGM_RD_W(BEDTEMPTABLE[i-1][0])) *
  567. (float)(PGM_RD_W(BEDTEMPTABLE[i][1]) - PGM_RD_W(BEDTEMPTABLE[i-1][1])) /
  568. (float)(PGM_RD_W(BEDTEMPTABLE[i][0]) - PGM_RD_W(BEDTEMPTABLE[i-1][0]));
  569. break;
  570. }
  571. }
  572. // Overflow: Set to last value in the table
  573. if (i == BEDTEMPTABLE_LEN) celsius = PGM_RD_W(BEDTEMPTABLE[i-1][1]);
  574. // temperature offset adjustment
  575. #ifdef BED_OFFSET
  576. float _offset = BED_OFFSET;
  577. float _offset_center = BED_OFFSET_CENTER;
  578. float _offset_start = BED_OFFSET_START;
  579. float _first_koef = (_offset / 2) / (_offset_center - _offset_start);
  580. float _second_koef = (_offset / 2) / (100 - _offset_center);
  581. if (celsius >= _offset_start && celsius <= _offset_center)
  582. {
  583. celsius = celsius + (_first_koef * (celsius - _offset_start));
  584. }
  585. else if (celsius > _offset_center && celsius <= 100)
  586. {
  587. celsius = celsius + (_first_koef * (_offset_center - _offset_start)) + ( _second_koef * ( celsius - ( 100 - _offset_center ) )) ;
  588. }
  589. else if (celsius > 100)
  590. {
  591. celsius = celsius + _offset;
  592. }
  593. #endif
  594. return celsius;
  595. #elif defined BED_USES_AD595
  596. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET;
  597. #else
  598. return 0;
  599. #endif
  600. }
  601. #ifdef AMBIENT_THERMISTOR
  602. static float analog2tempAmbient(int raw)
  603. {
  604. float celsius = 0;
  605. byte i;
  606. for (i=1; i<AMBIENTTEMPTABLE_LEN; i++)
  607. {
  608. if (PGM_RD_W(AMBIENTTEMPTABLE[i][0]) > raw)
  609. {
  610. celsius = PGM_RD_W(AMBIENTTEMPTABLE[i-1][1]) +
  611. (raw - PGM_RD_W(AMBIENTTEMPTABLE[i-1][0])) *
  612. (float)(PGM_RD_W(AMBIENTTEMPTABLE[i][1]) - PGM_RD_W(AMBIENTTEMPTABLE[i-1][1])) /
  613. (float)(PGM_RD_W(AMBIENTTEMPTABLE[i][0]) - PGM_RD_W(AMBIENTTEMPTABLE[i-1][0]));
  614. break;
  615. }
  616. }
  617. // Overflow: Set to last value in the table
  618. if (i == AMBIENTTEMPTABLE_LEN) celsius = PGM_RD_W(AMBIENTTEMPTABLE[i-1][1]);
  619. return celsius;
  620. }
  621. #endif //AMBIENT_THERMISTOR
  622. void soft_pwm_init()
  623. {
  624. #if MB(RUMBA) && ((TEMP_SENSOR_0==-1)||(TEMP_SENSOR_1==-1)||(TEMP_SENSOR_2==-1)||(TEMP_SENSOR_BED==-1))
  625. //disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
  626. MCUCR=(1<<JTD);
  627. MCUCR=(1<<JTD);
  628. #endif
  629. // Finish init of mult extruder arrays
  630. for(int e = 0; e < EXTRUDERS; e++) {
  631. // populate with the first value
  632. maxttemp[e] = maxttemp[0];
  633. #ifdef PIDTEMP
  634. iState_sum_min[e] = 0.0;
  635. iState_sum_max[e] = PID_INTEGRAL_DRIVE_MAX / cs.Ki;
  636. #endif //PIDTEMP
  637. #ifdef PIDTEMPBED
  638. temp_iState_min_bed = 0.0;
  639. temp_iState_max_bed = PID_INTEGRAL_DRIVE_MAX / cs.bedKi;
  640. #endif //PIDTEMPBED
  641. }
  642. #if defined(HEATER_0_PIN) && (HEATER_0_PIN > -1)
  643. SET_OUTPUT(HEATER_0_PIN);
  644. #endif
  645. #if defined(HEATER_1_PIN) && (HEATER_1_PIN > -1)
  646. SET_OUTPUT(HEATER_1_PIN);
  647. #endif
  648. #if defined(HEATER_2_PIN) && (HEATER_2_PIN > -1)
  649. SET_OUTPUT(HEATER_2_PIN);
  650. #endif
  651. #if defined(HEATER_BED_PIN) && (HEATER_BED_PIN > -1)
  652. SET_OUTPUT(HEATER_BED_PIN);
  653. #endif
  654. #if defined(FAN_PIN) && (FAN_PIN > -1)
  655. SET_OUTPUT(FAN_PIN);
  656. #ifdef FAST_PWM_FAN
  657. setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  658. #endif
  659. #ifdef FAN_SOFT_PWM
  660. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  661. #endif
  662. #endif
  663. #ifdef HEATER_0_USES_MAX6675
  664. #ifndef SDSUPPORT
  665. SET_OUTPUT(SCK_PIN);
  666. WRITE(SCK_PIN,0);
  667. SET_OUTPUT(MOSI_PIN);
  668. WRITE(MOSI_PIN,1);
  669. SET_INPUT(MISO_PIN);
  670. WRITE(MISO_PIN,1);
  671. #endif
  672. /* Using pinMode and digitalWrite, as that was the only way I could get it to compile */
  673. //Have to toggle SD card CS pin to low first, to enable firmware to talk with SD card
  674. pinMode(SS_PIN, OUTPUT);
  675. digitalWrite(SS_PIN,0);
  676. pinMode(MAX6675_SS, OUTPUT);
  677. digitalWrite(MAX6675_SS,1);
  678. #endif
  679. #ifdef HEATER_0_MINTEMP
  680. minttemp[0] = HEATER_0_MINTEMP;
  681. while(analog2temp(minttemp_raw[0], 0) < HEATER_0_MINTEMP) {
  682. #if HEATER_0_RAW_LO_TEMP < HEATER_0_RAW_HI_TEMP
  683. minttemp_raw[0] += OVERSAMPLENR;
  684. #else
  685. minttemp_raw[0] -= OVERSAMPLENR;
  686. #endif
  687. }
  688. #endif //MINTEMP
  689. #ifdef HEATER_0_MAXTEMP
  690. maxttemp[0] = HEATER_0_MAXTEMP;
  691. while(analog2temp(maxttemp_raw[0], 0) > HEATER_0_MAXTEMP) {
  692. #if HEATER_0_RAW_LO_TEMP < HEATER_0_RAW_HI_TEMP
  693. maxttemp_raw[0] -= OVERSAMPLENR;
  694. #else
  695. maxttemp_raw[0] += OVERSAMPLENR;
  696. #endif
  697. }
  698. #endif //MAXTEMP
  699. #if (EXTRUDERS > 1) && defined(HEATER_1_MINTEMP)
  700. minttemp[1] = HEATER_1_MINTEMP;
  701. while(analog2temp(minttemp_raw[1], 1) < HEATER_1_MINTEMP) {
  702. #if HEATER_1_RAW_LO_TEMP < HEATER_1_RAW_HI_TEMP
  703. minttemp_raw[1] += OVERSAMPLENR;
  704. #else
  705. minttemp_raw[1] -= OVERSAMPLENR;
  706. #endif
  707. }
  708. #endif // MINTEMP 1
  709. #if (EXTRUDERS > 1) && defined(HEATER_1_MAXTEMP)
  710. maxttemp[1] = HEATER_1_MAXTEMP;
  711. while(analog2temp(maxttemp_raw[1], 1) > HEATER_1_MAXTEMP) {
  712. #if HEATER_1_RAW_LO_TEMP < HEATER_1_RAW_HI_TEMP
  713. maxttemp_raw[1] -= OVERSAMPLENR;
  714. #else
  715. maxttemp_raw[1] += OVERSAMPLENR;
  716. #endif
  717. }
  718. #endif //MAXTEMP 1
  719. #if (EXTRUDERS > 2) && defined(HEATER_2_MINTEMP)
  720. minttemp[2] = HEATER_2_MINTEMP;
  721. while(analog2temp(minttemp_raw[2], 2) < HEATER_2_MINTEMP) {
  722. #if HEATER_2_RAW_LO_TEMP < HEATER_2_RAW_HI_TEMP
  723. minttemp_raw[2] += OVERSAMPLENR;
  724. #else
  725. minttemp_raw[2] -= OVERSAMPLENR;
  726. #endif
  727. }
  728. #endif //MINTEMP 2
  729. #if (EXTRUDERS > 2) && defined(HEATER_2_MAXTEMP)
  730. maxttemp[2] = HEATER_2_MAXTEMP;
  731. while(analog2temp(maxttemp_raw[2], 2) > HEATER_2_MAXTEMP) {
  732. #if HEATER_2_RAW_LO_TEMP < HEATER_2_RAW_HI_TEMP
  733. maxttemp_raw[2] -= OVERSAMPLENR;
  734. #else
  735. maxttemp_raw[2] += OVERSAMPLENR;
  736. #endif
  737. }
  738. #endif //MAXTEMP 2
  739. #ifdef BED_MINTEMP
  740. while(analog2tempBed(bed_minttemp_raw) < BED_MINTEMP) {
  741. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  742. bed_minttemp_raw += OVERSAMPLENR;
  743. #else
  744. bed_minttemp_raw -= OVERSAMPLENR;
  745. #endif
  746. }
  747. #endif //BED_MINTEMP
  748. #ifdef BED_MAXTEMP
  749. while(analog2tempBed(bed_maxttemp_raw) > BED_MAXTEMP) {
  750. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  751. bed_maxttemp_raw -= OVERSAMPLENR;
  752. #else
  753. bed_maxttemp_raw += OVERSAMPLENR;
  754. #endif
  755. }
  756. #endif //BED_MAXTEMP
  757. #ifdef AMBIENT_MINTEMP
  758. while(analog2tempAmbient(ambient_minttemp_raw) < AMBIENT_MINTEMP) {
  759. #if AMBIENT_RAW_LO_TEMP < AMBIENT_RAW_HI_TEMP
  760. ambient_minttemp_raw += OVERSAMPLENR;
  761. #else
  762. ambient_minttemp_raw -= OVERSAMPLENR;
  763. #endif
  764. }
  765. #endif //AMBIENT_MINTEMP
  766. #ifdef AMBIENT_MAXTEMP
  767. while(analog2tempAmbient(ambient_maxttemp_raw) > AMBIENT_MAXTEMP) {
  768. #if AMBIENT_RAW_LO_TEMP < AMBIENT_RAW_HI_TEMP
  769. ambient_maxttemp_raw -= OVERSAMPLENR;
  770. #else
  771. ambient_maxttemp_raw += OVERSAMPLENR;
  772. #endif
  773. }
  774. #endif //AMBIENT_MAXTEMP
  775. timer0_init(); //enables the heatbed timer.
  776. // timer2 already enabled earlier in the code
  777. // now enable the COMPB temperature interrupt
  778. OCR2B = 128;
  779. ENABLE_SOFT_PWM_INTERRUPT();
  780. timer4_init(); //for tone and Hotend fan PWM
  781. }
  782. #if (defined (TEMP_RUNAWAY_BED_HYSTERESIS) && TEMP_RUNAWAY_BED_TIMEOUT > 0) || (defined (TEMP_RUNAWAY_EXTRUDER_HYSTERESIS) && TEMP_RUNAWAY_EXTRUDER_TIMEOUT > 0)
  783. static void temp_runaway_check(uint8_t _heater_id, float _target_temperature, float _current_temperature, float _output, bool _isbed)
  784. {
  785. float __delta;
  786. float __hysteresis = 0;
  787. uint16_t __timeout = 0;
  788. bool temp_runaway_check_active = false;
  789. static float __preheat_start[2] = { 0,0}; //currently just bed and one extruder
  790. static uint8_t __preheat_counter[2] = { 0,0};
  791. static uint8_t __preheat_errors[2] = { 0,0};
  792. if (_millis() - temp_runaway_timer[_heater_id] > 2000)
  793. {
  794. #ifdef TEMP_RUNAWAY_BED_TIMEOUT
  795. if (_isbed)
  796. {
  797. __hysteresis = TEMP_RUNAWAY_BED_HYSTERESIS;
  798. __timeout = TEMP_RUNAWAY_BED_TIMEOUT;
  799. }
  800. #endif
  801. #ifdef TEMP_RUNAWAY_EXTRUDER_TIMEOUT
  802. if (!_isbed)
  803. {
  804. __hysteresis = TEMP_RUNAWAY_EXTRUDER_HYSTERESIS;
  805. __timeout = TEMP_RUNAWAY_EXTRUDER_TIMEOUT;
  806. }
  807. #endif
  808. temp_runaway_timer[_heater_id] = _millis();
  809. if (_output == 0)
  810. {
  811. temp_runaway_check_active = false;
  812. temp_runaway_error_counter[_heater_id] = 0;
  813. }
  814. if (temp_runaway_target[_heater_id] != _target_temperature)
  815. {
  816. if (_target_temperature > 0)
  817. {
  818. temp_runaway_status[_heater_id] = TempRunaway_PREHEAT;
  819. temp_runaway_target[_heater_id] = _target_temperature;
  820. __preheat_start[_heater_id] = _current_temperature;
  821. __preheat_counter[_heater_id] = 0;
  822. }
  823. else
  824. {
  825. temp_runaway_status[_heater_id] = TempRunaway_INACTIVE;
  826. temp_runaway_target[_heater_id] = _target_temperature;
  827. }
  828. }
  829. if ((_current_temperature < _target_temperature) && (temp_runaway_status[_heater_id] == TempRunaway_PREHEAT))
  830. {
  831. __preheat_counter[_heater_id]++;
  832. if (__preheat_counter[_heater_id] > ((_isbed) ? 16 : 8)) // periodicaly check if current temperature changes
  833. {
  834. /*SERIAL_ECHOPGM("Heater:");
  835. MYSERIAL.print(_heater_id);
  836. SERIAL_ECHOPGM(" T:");
  837. MYSERIAL.print(_current_temperature);
  838. SERIAL_ECHOPGM(" Tstart:");
  839. MYSERIAL.print(__preheat_start[_heater_id]);
  840. SERIAL_ECHOPGM(" delta:");
  841. MYSERIAL.print(_current_temperature-__preheat_start[_heater_id]);*/
  842. //-// if (_current_temperature - __preheat_start[_heater_id] < 2) {
  843. //-// if (_current_temperature - __preheat_start[_heater_id] < ((_isbed && (_current_temperature>105.0))?0.6:2.0)) {
  844. __delta=2.0;
  845. if(_isbed)
  846. {
  847. __delta=3.0;
  848. if(_current_temperature>90.0) __delta=2.0;
  849. if(_current_temperature>105.0) __delta=0.6;
  850. }
  851. if (_current_temperature - __preheat_start[_heater_id] < __delta) {
  852. __preheat_errors[_heater_id]++;
  853. /*SERIAL_ECHOPGM(" Preheat errors:");
  854. MYSERIAL.println(__preheat_errors[_heater_id]);*/
  855. }
  856. else {
  857. //SERIAL_ECHOLNPGM("");
  858. __preheat_errors[_heater_id] = 0;
  859. }
  860. if (__preheat_errors[_heater_id] > ((_isbed) ? 3 : 5))
  861. set_temp_error((_isbed?TempErrorSource::bed:TempErrorSource::hotend), _heater_id, TempErrorType::preheat);
  862. __preheat_start[_heater_id] = _current_temperature;
  863. __preheat_counter[_heater_id] = 0;
  864. }
  865. }
  866. //-// if (_current_temperature >= _target_temperature && temp_runaway_status[_heater_id] == TempRunaway_PREHEAT)
  867. if ((_current_temperature > (_target_temperature - __hysteresis)) && temp_runaway_status[_heater_id] == TempRunaway_PREHEAT)
  868. {
  869. /*SERIAL_ECHOPGM("Heater:");
  870. MYSERIAL.print(_heater_id);
  871. MYSERIAL.println(" ->tempRunaway");*/
  872. temp_runaway_status[_heater_id] = TempRunaway_ACTIVE;
  873. temp_runaway_check_active = false;
  874. temp_runaway_error_counter[_heater_id] = 0;
  875. }
  876. if (_output > 0)
  877. {
  878. temp_runaway_check_active = true;
  879. }
  880. if (temp_runaway_check_active)
  881. {
  882. // we are in range
  883. if ((_current_temperature > (_target_temperature - __hysteresis)) && (_current_temperature < (_target_temperature + __hysteresis)))
  884. {
  885. temp_runaway_check_active = false;
  886. temp_runaway_error_counter[_heater_id] = 0;
  887. }
  888. else
  889. {
  890. if (temp_runaway_status[_heater_id] > TempRunaway_PREHEAT)
  891. {
  892. temp_runaway_error_counter[_heater_id]++;
  893. if (temp_runaway_error_counter[_heater_id] * 2 > __timeout)
  894. set_temp_error((_isbed?TempErrorSource::bed:TempErrorSource::hotend), _heater_id, TempErrorType::runaway);
  895. }
  896. }
  897. }
  898. }
  899. }
  900. static void temp_runaway_stop(bool isPreheat, bool isBed)
  901. {
  902. if(IsStopped() == false) {
  903. if (isPreheat) {
  904. lcd_setalertstatuspgm(isBed? PSTR("BED PREHEAT ERROR") : PSTR("PREHEAT ERROR"), LCD_STATUS_CRITICAL);
  905. SERIAL_ERROR_START;
  906. if (isBed) {
  907. SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HEATBED)");
  908. } else {
  909. SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HOTEND)");
  910. }
  911. } else {
  912. lcd_setalertstatuspgm(isBed? PSTR("BED THERMAL RUNAWAY") : PSTR("THERMAL RUNAWAY"), LCD_STATUS_CRITICAL);
  913. SERIAL_ERROR_START;
  914. if (isBed) {
  915. SERIAL_ERRORLNPGM(" HEATBED THERMAL RUNAWAY");
  916. } else {
  917. SERIAL_ERRORLNPGM(" HOTEND THERMAL RUNAWAY");
  918. }
  919. }
  920. prusa_statistics(0);
  921. prusa_statistics(isPreheat? 91 : 90);
  922. }
  923. ThermalStop();
  924. }
  925. #endif
  926. //! signal a temperature error on both the lcd and serial
  927. //! @param type short error abbreviation (PROGMEM)
  928. //! @param e optional extruder index for hotend errors
  929. static void temp_error_messagepgm(const char* PROGMEM type, uint8_t e = EXTRUDERS)
  930. {
  931. char msg[LCD_WIDTH];
  932. strcpy_P(msg, PSTR("Err: "));
  933. strcat_P(msg, type);
  934. lcd_setalertstatus(msg, LCD_STATUS_CRITICAL);
  935. SERIAL_ERROR_START;
  936. if(e != EXTRUDERS) {
  937. SERIAL_ERROR((int)e);
  938. SERIAL_ERRORPGM(": ");
  939. }
  940. SERIAL_ERRORPGM("Heaters switched off. ");
  941. SERIAL_ERRORRPGM(type);
  942. SERIAL_ERRORLNPGM(" triggered!");
  943. }
  944. static void max_temp_error(uint8_t e) {
  945. if(IsStopped() == false) {
  946. temp_error_messagepgm(PSTR("MAXTEMP"), e);
  947. prusa_statistics(93);
  948. }
  949. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  950. ThermalStop();
  951. #endif
  952. }
  953. static void min_temp_error(uint8_t e) {
  954. static const char err[] PROGMEM = "MINTEMP";
  955. if(IsStopped() == false) {
  956. temp_error_messagepgm(err, e);
  957. prusa_statistics(92);
  958. }
  959. ThermalStop();
  960. }
  961. static void bed_max_temp_error(void) {
  962. if(IsStopped() == false) {
  963. temp_error_messagepgm(PSTR("MAXTEMP BED"));
  964. }
  965. ThermalStop();
  966. }
  967. static void bed_min_temp_error(void) {
  968. static const char err[] PROGMEM = "MINTEMP BED";
  969. if(IsStopped() == false) {
  970. temp_error_messagepgm(err);
  971. }
  972. ThermalStop();
  973. }
  974. #ifdef AMBIENT_THERMISTOR
  975. static void ambient_max_temp_error(void) {
  976. if(IsStopped() == false) {
  977. temp_error_messagepgm(PSTR("MAXTEMP AMB"));
  978. }
  979. ThermalStop();
  980. }
  981. static void ambient_min_temp_error(void) {
  982. if(IsStopped() == false) {
  983. temp_error_messagepgm(PSTR("MINTEMP AMB"));
  984. }
  985. ThermalStop();
  986. }
  987. #endif
  988. #ifdef HEATER_0_USES_MAX6675
  989. #define MAX6675_HEAT_INTERVAL 250
  990. long max6675_previous_millis = MAX6675_HEAT_INTERVAL;
  991. int max6675_temp = 2000;
  992. int read_max6675()
  993. {
  994. if (_millis() - max6675_previous_millis < MAX6675_HEAT_INTERVAL)
  995. return max6675_temp;
  996. max6675_previous_millis = _millis();
  997. max6675_temp = 0;
  998. #ifdef PRR
  999. PRR &= ~(1<<PRSPI);
  1000. #elif defined PRR0
  1001. PRR0 &= ~(1<<PRSPI);
  1002. #endif
  1003. SPCR = (1<<MSTR) | (1<<SPE) | (1<<SPR0);
  1004. // enable TT_MAX6675
  1005. WRITE(MAX6675_SS, 0);
  1006. // ensure 100ns delay - a bit extra is fine
  1007. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1008. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1009. // read MSB
  1010. SPDR = 0;
  1011. for (;(SPSR & (1<<SPIF)) == 0;);
  1012. max6675_temp = SPDR;
  1013. max6675_temp <<= 8;
  1014. // read LSB
  1015. SPDR = 0;
  1016. for (;(SPSR & (1<<SPIF)) == 0;);
  1017. max6675_temp |= SPDR;
  1018. // disable TT_MAX6675
  1019. WRITE(MAX6675_SS, 1);
  1020. if (max6675_temp & 4)
  1021. {
  1022. // thermocouple open
  1023. max6675_temp = 2000;
  1024. }
  1025. else
  1026. {
  1027. max6675_temp = max6675_temp >> 3;
  1028. }
  1029. return max6675_temp;
  1030. }
  1031. #endif
  1032. #ifdef BABYSTEPPING
  1033. FORCE_INLINE static void applyBabysteps() {
  1034. for(uint8_t axis=0;axis<3;axis++)
  1035. {
  1036. int curTodo=babystepsTodo[axis]; //get rid of volatile for performance
  1037. if(curTodo>0)
  1038. {
  1039. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1040. babystep(axis,/*fwd*/true);
  1041. babystepsTodo[axis]--; //less to do next time
  1042. }
  1043. }
  1044. else
  1045. if(curTodo<0)
  1046. {
  1047. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1048. babystep(axis,/*fwd*/false);
  1049. babystepsTodo[axis]++; //less to do next time
  1050. }
  1051. }
  1052. }
  1053. }
  1054. #endif //BABYSTEPPING
  1055. FORCE_INLINE static void soft_pwm_core()
  1056. {
  1057. static uint8_t pwm_count = (1 << SOFT_PWM_SCALE);
  1058. static uint8_t soft_pwm_0;
  1059. #ifdef SLOW_PWM_HEATERS
  1060. static unsigned char slow_pwm_count = 0;
  1061. static unsigned char state_heater_0 = 0;
  1062. static unsigned char state_timer_heater_0 = 0;
  1063. #endif
  1064. #if (EXTRUDERS > 1) || defined(HEATERS_PARALLEL)
  1065. static unsigned char soft_pwm_1;
  1066. #ifdef SLOW_PWM_HEATERS
  1067. static unsigned char state_heater_1 = 0;
  1068. static unsigned char state_timer_heater_1 = 0;
  1069. #endif
  1070. #endif
  1071. #if EXTRUDERS > 2
  1072. static unsigned char soft_pwm_2;
  1073. #ifdef SLOW_PWM_HEATERS
  1074. static unsigned char state_heater_2 = 0;
  1075. static unsigned char state_timer_heater_2 = 0;
  1076. #endif
  1077. #endif
  1078. #if HEATER_BED_PIN > -1
  1079. // @@DR static unsigned char soft_pwm_b;
  1080. #ifdef SLOW_PWM_HEATERS
  1081. static unsigned char state_heater_b = 0;
  1082. static unsigned char state_timer_heater_b = 0;
  1083. #endif
  1084. #endif
  1085. #if defined(FILWIDTH_PIN) &&(FILWIDTH_PIN > -1)
  1086. static unsigned long raw_filwidth_value = 0; //added for filament width sensor
  1087. #endif
  1088. #ifndef SLOW_PWM_HEATERS
  1089. /*
  1090. * standard PWM modulation
  1091. */
  1092. if (pwm_count == 0)
  1093. {
  1094. soft_pwm_0 = soft_pwm[0];
  1095. if(soft_pwm_0 > 0)
  1096. {
  1097. WRITE(HEATER_0_PIN,1);
  1098. #ifdef HEATERS_PARALLEL
  1099. WRITE(HEATER_1_PIN,1);
  1100. #endif
  1101. } else WRITE(HEATER_0_PIN,0);
  1102. #if EXTRUDERS > 1
  1103. soft_pwm_1 = soft_pwm[1];
  1104. if(soft_pwm_1 > 0) WRITE(HEATER_1_PIN,1); else WRITE(HEATER_1_PIN,0);
  1105. #endif
  1106. #if EXTRUDERS > 2
  1107. soft_pwm_2 = soft_pwm[2];
  1108. if(soft_pwm_2 > 0) WRITE(HEATER_2_PIN,1); else WRITE(HEATER_2_PIN,0);
  1109. #endif
  1110. }
  1111. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1112. #if 0 // @@DR vypnuto pro hw pwm bedu
  1113. // tuhle prasarnu bude potreba poustet ve stanovenych intervalech, jinak nemam moc sanci zareagovat
  1114. // teoreticky by se tato cast uz vubec nemusela poustet
  1115. if ((pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1)) == 0)
  1116. {
  1117. soft_pwm_b = soft_pwm_bed >> (7 - HEATER_BED_SOFT_PWM_BITS);
  1118. # ifndef SYSTEM_TIMER_2
  1119. // tady budu krokovat pomalou frekvenci na automatu - tohle je rizeni spinani a rozepinani
  1120. // jako ridici frekvenci mam 2khz, jako vystupni frekvenci mam 30hz
  1121. // 2kHz jsou ovsem ve slysitelnem pasmu, mozna bude potreba jit s frekvenci nahoru (a tomu taky prizpusobit ostatni veci)
  1122. // Teoreticky bych mohl stahnout OCR0B citac na 6, cimz bych se dostal nekam ke 40khz a tady potom honit PWM rychleji nebo i pomaleji
  1123. // to nicemu nevadi. Soft PWM scale by se 20x zvetsilo (no dobre, 16x), cimz by se to posunulo k puvodnimu 30Hz PWM
  1124. //if(soft_pwm_b > 0) WRITE(HEATER_BED_PIN,1); else WRITE(HEATER_BED_PIN,0);
  1125. # endif //SYSTEM_TIMER_2
  1126. }
  1127. #endif
  1128. #endif
  1129. #ifdef FAN_SOFT_PWM
  1130. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1131. {
  1132. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1133. if(soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1134. }
  1135. #endif
  1136. if(soft_pwm_0 < pwm_count)
  1137. {
  1138. WRITE(HEATER_0_PIN,0);
  1139. #ifdef HEATERS_PARALLEL
  1140. WRITE(HEATER_1_PIN,0);
  1141. #endif
  1142. }
  1143. #if EXTRUDERS > 1
  1144. if(soft_pwm_1 < pwm_count) WRITE(HEATER_1_PIN,0);
  1145. #endif
  1146. #if EXTRUDERS > 2
  1147. if(soft_pwm_2 < pwm_count) WRITE(HEATER_2_PIN,0);
  1148. #endif
  1149. #if 0 // @@DR
  1150. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1151. if (soft_pwm_b < (pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1))){
  1152. //WRITE(HEATER_BED_PIN,0);
  1153. }
  1154. //WRITE(HEATER_BED_PIN, pwm_count & 1 );
  1155. #endif
  1156. #endif
  1157. #ifdef FAN_SOFT_PWM
  1158. if (soft_pwm_fan < (pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1))) WRITE(FAN_PIN,0);
  1159. #endif
  1160. pwm_count += (1 << SOFT_PWM_SCALE);
  1161. pwm_count &= 0x7f;
  1162. #else //ifndef SLOW_PWM_HEATERS
  1163. /*
  1164. * SLOW PWM HEATERS
  1165. *
  1166. * for heaters drived by relay
  1167. */
  1168. #ifndef MIN_STATE_TIME
  1169. #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
  1170. #endif
  1171. if (slow_pwm_count == 0) {
  1172. // EXTRUDER 0
  1173. soft_pwm_0 = soft_pwm[0];
  1174. if (soft_pwm_0 > 0) {
  1175. // turn ON heather only if the minimum time is up
  1176. if (state_timer_heater_0 == 0) {
  1177. // if change state set timer
  1178. if (state_heater_0 == 0) {
  1179. state_timer_heater_0 = MIN_STATE_TIME;
  1180. }
  1181. state_heater_0 = 1;
  1182. WRITE(HEATER_0_PIN, 1);
  1183. #ifdef HEATERS_PARALLEL
  1184. WRITE(HEATER_1_PIN, 1);
  1185. #endif
  1186. }
  1187. } else {
  1188. // turn OFF heather only if the minimum time is up
  1189. if (state_timer_heater_0 == 0) {
  1190. // if change state set timer
  1191. if (state_heater_0 == 1) {
  1192. state_timer_heater_0 = MIN_STATE_TIME;
  1193. }
  1194. state_heater_0 = 0;
  1195. WRITE(HEATER_0_PIN, 0);
  1196. #ifdef HEATERS_PARALLEL
  1197. WRITE(HEATER_1_PIN, 0);
  1198. #endif
  1199. }
  1200. }
  1201. #if EXTRUDERS > 1
  1202. // EXTRUDER 1
  1203. soft_pwm_1 = soft_pwm[1];
  1204. if (soft_pwm_1 > 0) {
  1205. // turn ON heather only if the minimum time is up
  1206. if (state_timer_heater_1 == 0) {
  1207. // if change state set timer
  1208. if (state_heater_1 == 0) {
  1209. state_timer_heater_1 = MIN_STATE_TIME;
  1210. }
  1211. state_heater_1 = 1;
  1212. WRITE(HEATER_1_PIN, 1);
  1213. }
  1214. } else {
  1215. // turn OFF heather only if the minimum time is up
  1216. if (state_timer_heater_1 == 0) {
  1217. // if change state set timer
  1218. if (state_heater_1 == 1) {
  1219. state_timer_heater_1 = MIN_STATE_TIME;
  1220. }
  1221. state_heater_1 = 0;
  1222. WRITE(HEATER_1_PIN, 0);
  1223. }
  1224. }
  1225. #endif
  1226. #if EXTRUDERS > 2
  1227. // EXTRUDER 2
  1228. soft_pwm_2 = soft_pwm[2];
  1229. if (soft_pwm_2 > 0) {
  1230. // turn ON heather only if the minimum time is up
  1231. if (state_timer_heater_2 == 0) {
  1232. // if change state set timer
  1233. if (state_heater_2 == 0) {
  1234. state_timer_heater_2 = MIN_STATE_TIME;
  1235. }
  1236. state_heater_2 = 1;
  1237. WRITE(HEATER_2_PIN, 1);
  1238. }
  1239. } else {
  1240. // turn OFF heather only if the minimum time is up
  1241. if (state_timer_heater_2 == 0) {
  1242. // if change state set timer
  1243. if (state_heater_2 == 1) {
  1244. state_timer_heater_2 = MIN_STATE_TIME;
  1245. }
  1246. state_heater_2 = 0;
  1247. WRITE(HEATER_2_PIN, 0);
  1248. }
  1249. }
  1250. #endif
  1251. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1252. // BED
  1253. soft_pwm_b = soft_pwm_bed;
  1254. if (soft_pwm_b > 0) {
  1255. // turn ON heather only if the minimum time is up
  1256. if (state_timer_heater_b == 0) {
  1257. // if change state set timer
  1258. if (state_heater_b == 0) {
  1259. state_timer_heater_b = MIN_STATE_TIME;
  1260. }
  1261. state_heater_b = 1;
  1262. //WRITE(HEATER_BED_PIN, 1);
  1263. }
  1264. } else {
  1265. // turn OFF heather only if the minimum time is up
  1266. if (state_timer_heater_b == 0) {
  1267. // if change state set timer
  1268. if (state_heater_b == 1) {
  1269. state_timer_heater_b = MIN_STATE_TIME;
  1270. }
  1271. state_heater_b = 0;
  1272. WRITE(HEATER_BED_PIN, 0);
  1273. }
  1274. }
  1275. #endif
  1276. } // if (slow_pwm_count == 0)
  1277. // EXTRUDER 0
  1278. if (soft_pwm_0 < slow_pwm_count) {
  1279. // turn OFF heather only if the minimum time is up
  1280. if (state_timer_heater_0 == 0) {
  1281. // if change state set timer
  1282. if (state_heater_0 == 1) {
  1283. state_timer_heater_0 = MIN_STATE_TIME;
  1284. }
  1285. state_heater_0 = 0;
  1286. WRITE(HEATER_0_PIN, 0);
  1287. #ifdef HEATERS_PARALLEL
  1288. WRITE(HEATER_1_PIN, 0);
  1289. #endif
  1290. }
  1291. }
  1292. #if EXTRUDERS > 1
  1293. // EXTRUDER 1
  1294. if (soft_pwm_1 < slow_pwm_count) {
  1295. // turn OFF heather only if the minimum time is up
  1296. if (state_timer_heater_1 == 0) {
  1297. // if change state set timer
  1298. if (state_heater_1 == 1) {
  1299. state_timer_heater_1 = MIN_STATE_TIME;
  1300. }
  1301. state_heater_1 = 0;
  1302. WRITE(HEATER_1_PIN, 0);
  1303. }
  1304. }
  1305. #endif
  1306. #if EXTRUDERS > 2
  1307. // EXTRUDER 2
  1308. if (soft_pwm_2 < slow_pwm_count) {
  1309. // turn OFF heather only if the minimum time is up
  1310. if (state_timer_heater_2 == 0) {
  1311. // if change state set timer
  1312. if (state_heater_2 == 1) {
  1313. state_timer_heater_2 = MIN_STATE_TIME;
  1314. }
  1315. state_heater_2 = 0;
  1316. WRITE(HEATER_2_PIN, 0);
  1317. }
  1318. }
  1319. #endif
  1320. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1321. // BED
  1322. if (soft_pwm_b < slow_pwm_count) {
  1323. // turn OFF heather only if the minimum time is up
  1324. if (state_timer_heater_b == 0) {
  1325. // if change state set timer
  1326. if (state_heater_b == 1) {
  1327. state_timer_heater_b = MIN_STATE_TIME;
  1328. }
  1329. state_heater_b = 0;
  1330. WRITE(HEATER_BED_PIN, 0);
  1331. }
  1332. }
  1333. #endif
  1334. #ifdef FAN_SOFT_PWM
  1335. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1336. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1337. if (soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1338. }
  1339. if (soft_pwm_fan < pwm_count) WRITE(FAN_PIN,0);
  1340. #endif
  1341. pwm_count += (1 << SOFT_PWM_SCALE);
  1342. pwm_count &= 0x7f;
  1343. // increment slow_pwm_count only every 64 pwm_count circa 65.5ms
  1344. if ((pwm_count % 64) == 0) {
  1345. slow_pwm_count++;
  1346. slow_pwm_count &= 0x7f;
  1347. // Extruder 0
  1348. if (state_timer_heater_0 > 0) {
  1349. state_timer_heater_0--;
  1350. }
  1351. #if EXTRUDERS > 1
  1352. // Extruder 1
  1353. if (state_timer_heater_1 > 0)
  1354. state_timer_heater_1--;
  1355. #endif
  1356. #if EXTRUDERS > 2
  1357. // Extruder 2
  1358. if (state_timer_heater_2 > 0)
  1359. state_timer_heater_2--;
  1360. #endif
  1361. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1362. // Bed
  1363. if (state_timer_heater_b > 0)
  1364. state_timer_heater_b--;
  1365. #endif
  1366. } //if ((pwm_count % 64) == 0) {
  1367. #endif //ifndef SLOW_PWM_HEATERS
  1368. }
  1369. FORCE_INLINE static void soft_pwm_isr()
  1370. {
  1371. lcd_buttons_update();
  1372. soft_pwm_core();
  1373. #ifdef BABYSTEPPING
  1374. applyBabysteps();
  1375. #endif //BABYSTEPPING
  1376. // Check if a stack overflow happened
  1377. if (!SdFatUtil::test_stack_integrity()) stack_error();
  1378. #if (defined(FANCHECK) && defined(TACH_0) && (TACH_0 > -1))
  1379. readFanTach();
  1380. #endif //(defined(TACH_0))
  1381. }
  1382. // Timer2 (originaly timer0) is shared with millies
  1383. #ifdef SYSTEM_TIMER_2
  1384. ISR(TIMER2_COMPB_vect)
  1385. #else //SYSTEM_TIMER_2
  1386. ISR(TIMER0_COMPB_vect)
  1387. #endif //SYSTEM_TIMER_2
  1388. {
  1389. DISABLE_SOFT_PWM_INTERRUPT();
  1390. NONATOMIC_BLOCK(NONATOMIC_FORCEOFF) {
  1391. soft_pwm_isr();
  1392. }
  1393. ENABLE_SOFT_PWM_INTERRUPT();
  1394. }
  1395. void check_max_temp_raw()
  1396. {
  1397. //heater
  1398. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1399. if (current_temperature_raw[0] <= maxttemp_raw[0]) {
  1400. #else
  1401. if (current_temperature_raw[0] >= maxttemp_raw[0]) {
  1402. #endif
  1403. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::max);
  1404. }
  1405. //bed
  1406. #if defined(BED_MAXTEMP) && (TEMP_SENSOR_BED != 0)
  1407. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1408. if (current_temperature_bed_raw <= bed_maxttemp_raw) {
  1409. #else
  1410. if (current_temperature_bed_raw >= bed_maxttemp_raw) {
  1411. #endif
  1412. set_temp_error(TempErrorSource::bed, 0, TempErrorType::max);
  1413. }
  1414. #endif
  1415. //ambient
  1416. #if defined(AMBIENT_MAXTEMP) && (TEMP_SENSOR_AMBIENT != 0)
  1417. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1418. if (current_temperature_raw_ambient <= ambient_maxttemp_raw) {
  1419. #else
  1420. if (current_temperature_raw_ambient >= ambient_maxttemp_raw) {
  1421. #endif
  1422. set_temp_error(TempErrorSource::ambient, 0, TempErrorType::max);
  1423. }
  1424. #endif
  1425. }
  1426. //! number of repeating the same state with consecutive step() calls
  1427. //! used to slow down text switching
  1428. struct alert_automaton_mintemp {
  1429. const char *m2;
  1430. alert_automaton_mintemp(const char *m2):m2(m2){}
  1431. private:
  1432. enum { ALERT_AUTOMATON_SPEED_DIV = 5 };
  1433. enum class States : uint8_t { Init = 0, TempAboveMintemp, ShowPleaseRestart, ShowMintemp };
  1434. States state = States::Init;
  1435. uint8_t repeat = ALERT_AUTOMATON_SPEED_DIV;
  1436. void substep(const char* next_msg, States next_state){
  1437. if( repeat == 0 ){
  1438. state = next_state; // advance to the next state
  1439. lcd_setalertstatuspgm(next_msg, LCD_STATUS_CRITICAL);
  1440. repeat = ALERT_AUTOMATON_SPEED_DIV; // and prepare repeating for it too
  1441. } else {
  1442. --repeat;
  1443. }
  1444. }
  1445. public:
  1446. //! brief state automaton step routine
  1447. //! @param current_temp current hotend/bed temperature (for computing simple hysteresis)
  1448. //! @param mintemp minimal temperature including hysteresis to check current_temp against
  1449. void step(float current_temp, float mintemp){
  1450. static const char m1[] PROGMEM = "Please restart";
  1451. switch(state){
  1452. case States::Init: // initial state - check hysteresis
  1453. if( current_temp > mintemp ){
  1454. lcd_setalertstatuspgm(m2, LCD_STATUS_CRITICAL);
  1455. state = States::TempAboveMintemp;
  1456. }
  1457. // otherwise keep the Err MINTEMP alert message on the display,
  1458. // i.e. do not transfer to state 1
  1459. break;
  1460. case States::TempAboveMintemp: // the temperature has risen above the hysteresis check
  1461. case States::ShowMintemp: // displaying "MINTEMP fixed"
  1462. substep(m1, States::ShowPleaseRestart);
  1463. break;
  1464. case States::ShowPleaseRestart: // displaying "Please restart"
  1465. substep(m2, States::ShowMintemp);
  1466. break;
  1467. }
  1468. }
  1469. };
  1470. static const char m2hotend[] PROGMEM = "MINTEMP HOTEND fixed";
  1471. static const char m2bed[] PROGMEM = "MINTEMP BED fixed";
  1472. static alert_automaton_mintemp alert_automaton_hotend(m2hotend), alert_automaton_bed(m2bed);
  1473. void check_min_temp_heater0()
  1474. {
  1475. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1476. if (current_temperature_raw[0] >= minttemp_raw[0]) {
  1477. #else
  1478. if (current_temperature_raw[0] <= minttemp_raw[0]) {
  1479. #endif
  1480. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::min);
  1481. }
  1482. }
  1483. void check_min_temp_bed()
  1484. {
  1485. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1486. if (current_temperature_bed_raw >= bed_minttemp_raw) {
  1487. #else
  1488. if (current_temperature_bed_raw <= bed_minttemp_raw) {
  1489. #endif
  1490. set_temp_error(TempErrorSource::bed, 0, TempErrorType::min);
  1491. }
  1492. }
  1493. #ifdef AMBIENT_MINTEMP
  1494. void check_min_temp_ambient()
  1495. {
  1496. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1497. if (current_temperature_raw_ambient >= ambient_minttemp_raw) {
  1498. #else
  1499. if (current_temperature_raw_ambient <= ambient_minttemp_raw) {
  1500. #endif
  1501. set_temp_error(TempErrorSource::ambient, 0, TempErrorType::min);
  1502. }
  1503. }
  1504. #endif
  1505. void handle_temp_error()
  1506. {
  1507. // relay to the original handler
  1508. switch((TempErrorType)temp_error_state.type) {
  1509. case TempErrorType::min:
  1510. switch((TempErrorSource)temp_error_state.source) {
  1511. case TempErrorSource::hotend:
  1512. if(temp_error_state.assert) {
  1513. min_temp_error(temp_error_state.index);
  1514. } else {
  1515. // no recovery, just force the user to restart the printer
  1516. // which is a safer variant than just continuing printing
  1517. // The automaton also checks for hysteresis - the temperature must have reached a few degrees above the MINTEMP, before
  1518. // we shall signalize, that MINTEMP has been fixed
  1519. // Code notice: normally the alert_automaton instance would have been placed here
  1520. // as static alert_automaton_mintemp alert_automaton_hotend, but
  1521. alert_automaton_hotend.step(current_temperature[0], minttemp[0] + TEMP_HYSTERESIS);
  1522. }
  1523. break;
  1524. case TempErrorSource::bed:
  1525. if(temp_error_state.assert) {
  1526. bed_min_temp_error();
  1527. } else {
  1528. // no recovery, just force the user to restart the printer
  1529. // which is a safer variant than just continuing printing
  1530. alert_automaton_bed.step(current_temperature_bed, BED_MINTEMP + TEMP_HYSTERESIS);
  1531. }
  1532. break;
  1533. #ifdef AMBIENT_THERMISTOR
  1534. case TempErrorSource::ambient:
  1535. ambient_min_temp_error();
  1536. break;
  1537. #endif
  1538. }
  1539. break;
  1540. case TempErrorType::max:
  1541. switch((TempErrorSource)temp_error_state.source) {
  1542. case TempErrorSource::hotend:
  1543. max_temp_error(temp_error_state.index);
  1544. break;
  1545. case TempErrorSource::bed:
  1546. bed_max_temp_error();
  1547. break;
  1548. #ifdef AMBIENT_THERMISTOR
  1549. case TempErrorSource::ambient:
  1550. ambient_max_temp_error();
  1551. break;
  1552. #endif
  1553. }
  1554. break;
  1555. case TempErrorType::preheat:
  1556. case TempErrorType::runaway:
  1557. switch((TempErrorSource)temp_error_state.source) {
  1558. case TempErrorSource::hotend:
  1559. case TempErrorSource::bed:
  1560. temp_runaway_stop(
  1561. ((TempErrorType)temp_error_state.type == TempErrorType::preheat),
  1562. ((TempErrorSource)temp_error_state.source == TempErrorSource::bed));
  1563. break;
  1564. #ifdef AMBIENT_THERMISTOR
  1565. case TempErrorSource::ambient:
  1566. // not needed
  1567. break;
  1568. #endif
  1569. }
  1570. break;
  1571. #ifdef TEMP_MODEL
  1572. case TempErrorType::model:
  1573. if(temp_error_state.assert) {
  1574. if(IsStopped() == false) {
  1575. SERIAL_ECHOLNPGM("TM: error triggered!");
  1576. }
  1577. ThermalStop(true);
  1578. WRITE(BEEPER, HIGH);
  1579. } else {
  1580. temp_error_state.v = 0;
  1581. WRITE(BEEPER, LOW);
  1582. // hotend error was transitory and disappeared, re-enable bed
  1583. if (!target_temperature_bed)
  1584. target_temperature_bed = saved_bed_temperature;
  1585. SERIAL_ECHOLNPGM("TM: error cleared");
  1586. }
  1587. break;
  1588. #endif
  1589. }
  1590. }
  1591. #ifdef PIDTEMP
  1592. // Apply the scale factors to the PID values
  1593. float scalePID_i(float i)
  1594. {
  1595. return i*PID_dT;
  1596. }
  1597. float unscalePID_i(float i)
  1598. {
  1599. return i/PID_dT;
  1600. }
  1601. float scalePID_d(float d)
  1602. {
  1603. return d/PID_dT;
  1604. }
  1605. float unscalePID_d(float d)
  1606. {
  1607. return d*PID_dT;
  1608. }
  1609. #endif //PIDTEMP
  1610. #ifdef PINDA_THERMISTOR
  1611. //! @brief PINDA thermistor detected
  1612. //!
  1613. //! @retval true firmware should do temperature compensation and allow calibration
  1614. //! @retval false PINDA thermistor is not detected, disable temperature compensation and calibration
  1615. //! @retval true/false when forced via LCD menu Settings->HW Setup->SuperPINDA
  1616. //!
  1617. bool has_temperature_compensation()
  1618. {
  1619. #ifdef SUPERPINDA_SUPPORT
  1620. #ifdef PINDA_TEMP_COMP
  1621. uint8_t pinda_temp_compensation = eeprom_read_byte((uint8_t*)EEPROM_PINDA_TEMP_COMPENSATION);
  1622. if (pinda_temp_compensation == EEPROM_EMPTY_VALUE) //Unkown PINDA temp compenstation, so check it.
  1623. {
  1624. #endif //PINDA_TEMP_COMP
  1625. return (current_temperature_pinda >= PINDA_MINTEMP) ? true : false;
  1626. #ifdef PINDA_TEMP_COMP
  1627. }
  1628. else if (pinda_temp_compensation == 0) return true; //Overwritten via LCD menu SuperPINDA [No]
  1629. else return false; //Overwritten via LCD menu SuperPINDA [YES]
  1630. #endif //PINDA_TEMP_COMP
  1631. #else
  1632. return true;
  1633. #endif
  1634. }
  1635. #endif //PINDA_THERMISTOR
  1636. // RAII helper class to run a code block with temp_mgr_isr disabled
  1637. class TempMgrGuard
  1638. {
  1639. bool temp_mgr_state;
  1640. public:
  1641. TempMgrGuard() {
  1642. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1643. temp_mgr_state = TEMP_MGR_INTERRUPT_STATE();
  1644. DISABLE_TEMP_MGR_INTERRUPT();
  1645. }
  1646. }
  1647. ~TempMgrGuard() throw() {
  1648. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1649. if(temp_mgr_state) ENABLE_TEMP_MGR_INTERRUPT();
  1650. }
  1651. }
  1652. };
  1653. void temp_mgr_init()
  1654. {
  1655. // initialize the ADC and start a conversion
  1656. adc_init();
  1657. adc_start_cycle();
  1658. // initialize temperature timer
  1659. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1660. // CTC
  1661. TCCRxB &= ~(1<<WGMx3);
  1662. TCCRxB |= (1<<WGMx2);
  1663. TCCRxA &= ~(1<<WGMx1);
  1664. TCCRxA &= ~(1<<WGMx0);
  1665. // output mode = 00 (disconnected)
  1666. TCCRxA &= ~(3<<COMxA0);
  1667. TCCRxA &= ~(3<<COMxB0);
  1668. // x/256 prescaler
  1669. TCCRxB |= (1<<CSx2);
  1670. TCCRxB &= ~(1<<CSx1);
  1671. TCCRxB &= ~(1<<CSx0);
  1672. // reset counter
  1673. TCNTx = 0;
  1674. OCRxA = TEMP_TIM_OCRA_OVF;
  1675. // clear pending interrupts, enable COMPA
  1676. TEMP_MGR_INT_FLAG_CLEAR();
  1677. ENABLE_TEMP_MGR_INTERRUPT();
  1678. }
  1679. }
  1680. static void pid_heater(uint8_t e, const float current, const int target)
  1681. {
  1682. float pid_input;
  1683. float pid_output;
  1684. #ifdef PIDTEMP
  1685. pid_input = current;
  1686. #ifndef PID_OPENLOOP
  1687. if(target == 0) {
  1688. pid_output = 0;
  1689. pid_reset[e] = true;
  1690. } else {
  1691. pid_error[e] = target - pid_input;
  1692. if(pid_reset[e]) {
  1693. iState_sum[e] = 0.0;
  1694. dTerm[e] = 0.0; // 'dState_last[e]' initial setting is not necessary (see end of if-statement)
  1695. pid_reset[e] = false;
  1696. }
  1697. #ifndef PonM
  1698. pTerm[e] = cs.Kp * pid_error[e];
  1699. iState_sum[e] += pid_error[e];
  1700. iState_sum[e] = constrain(iState_sum[e], iState_sum_min[e], iState_sum_max[e]);
  1701. iTerm[e] = cs.Ki * iState_sum[e];
  1702. // PID_K1 defined in Configuration.h in the PID settings
  1703. #define K2 (1.0-PID_K1)
  1704. dTerm[e] = (cs.Kd * (pid_input - dState_last[e]))*K2 + (PID_K1 * dTerm[e]); // e.g. digital filtration of derivative term changes
  1705. pid_output = pTerm[e] + iTerm[e] - dTerm[e]; // subtraction due to "Derivative on Measurement" method (i.e. derivative of input instead derivative of error is used)
  1706. if (pid_output > PID_MAX) {
  1707. if (pid_error[e] > 0 ) iState_sum[e] -= pid_error[e]; // conditional un-integration
  1708. pid_output=PID_MAX;
  1709. } else if (pid_output < 0) {
  1710. if (pid_error[e] < 0 ) iState_sum[e] -= pid_error[e]; // conditional un-integration
  1711. pid_output=0;
  1712. }
  1713. #else // PonM ("Proportional on Measurement" method)
  1714. iState_sum[e] += cs.Ki * pid_error[e];
  1715. iState_sum[e] -= cs.Kp * (pid_input - dState_last[e]);
  1716. iState_sum[e] = constrain(iState_sum[e], 0, PID_INTEGRAL_DRIVE_MAX);
  1717. dTerm[e] = cs.Kd * (pid_input - dState_last[e]);
  1718. pid_output = iState_sum[e] - dTerm[e]; // subtraction due to "Derivative on Measurement" method (i.e. derivative of input instead derivative of error is used)
  1719. pid_output = constrain(pid_output, 0, PID_MAX);
  1720. #endif // PonM
  1721. }
  1722. dState_last[e] = pid_input;
  1723. #else //PID_OPENLOOP
  1724. pid_output = constrain(target[e], 0, PID_MAX);
  1725. #endif //PID_OPENLOOP
  1726. #ifdef PID_DEBUG
  1727. SERIAL_ECHO_START;
  1728. SERIAL_ECHO(" PID_DEBUG ");
  1729. SERIAL_ECHO(e);
  1730. SERIAL_ECHO(": Input ");
  1731. SERIAL_ECHO(pid_input);
  1732. SERIAL_ECHO(" Output ");
  1733. SERIAL_ECHO(pid_output);
  1734. SERIAL_ECHO(" pTerm ");
  1735. SERIAL_ECHO(pTerm[e]);
  1736. SERIAL_ECHO(" iTerm ");
  1737. SERIAL_ECHO(iTerm[e]);
  1738. SERIAL_ECHO(" dTerm ");
  1739. SERIAL_ECHOLN(-dTerm[e]);
  1740. #endif //PID_DEBUG
  1741. #else /* PID off */
  1742. pid_output = 0;
  1743. if(current[e] < target[e]) {
  1744. pid_output = PID_MAX;
  1745. }
  1746. #endif
  1747. // Check if temperature is within the correct range
  1748. if((current < maxttemp[e]) && (target != 0))
  1749. soft_pwm[e] = (int)pid_output >> 1;
  1750. else
  1751. soft_pwm[e] = 0;
  1752. }
  1753. static void pid_bed(const float current, const int target)
  1754. {
  1755. float pid_input;
  1756. float pid_output;
  1757. #ifndef PIDTEMPBED
  1758. if(_millis() - previous_millis_bed_heater < BED_CHECK_INTERVAL)
  1759. return;
  1760. previous_millis_bed_heater = _millis();
  1761. #endif
  1762. #if TEMP_SENSOR_BED != 0
  1763. #ifdef PIDTEMPBED
  1764. pid_input = current;
  1765. #ifndef PID_OPENLOOP
  1766. pid_error_bed = target - pid_input;
  1767. pTerm_bed = cs.bedKp * pid_error_bed;
  1768. temp_iState_bed += pid_error_bed;
  1769. temp_iState_bed = constrain(temp_iState_bed, temp_iState_min_bed, temp_iState_max_bed);
  1770. iTerm_bed = cs.bedKi * temp_iState_bed;
  1771. //PID_K1 defined in Configuration.h in the PID settings
  1772. #define K2 (1.0-PID_K1)
  1773. dTerm_bed= (cs.bedKd * (pid_input - temp_dState_bed))*K2 + (PID_K1 * dTerm_bed);
  1774. temp_dState_bed = pid_input;
  1775. pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
  1776. if (pid_output > MAX_BED_POWER) {
  1777. if (pid_error_bed > 0 ) temp_iState_bed -= pid_error_bed; // conditional un-integration
  1778. pid_output=MAX_BED_POWER;
  1779. } else if (pid_output < 0){
  1780. if (pid_error_bed < 0 ) temp_iState_bed -= pid_error_bed; // conditional un-integration
  1781. pid_output=0;
  1782. }
  1783. #else
  1784. pid_output = constrain(target, 0, MAX_BED_POWER);
  1785. #endif //PID_OPENLOOP
  1786. if(current < BED_MAXTEMP)
  1787. {
  1788. soft_pwm_bed = (int)pid_output >> 1;
  1789. timer02_set_pwm0(soft_pwm_bed << 1);
  1790. }
  1791. else
  1792. {
  1793. soft_pwm_bed = 0;
  1794. timer02_set_pwm0(soft_pwm_bed << 1);
  1795. }
  1796. #elif !defined(BED_LIMIT_SWITCHING)
  1797. // Check if temperature is within the correct range
  1798. if(current < BED_MAXTEMP)
  1799. {
  1800. if(current >= target)
  1801. {
  1802. soft_pwm_bed = 0;
  1803. timer02_set_pwm0(soft_pwm_bed << 1);
  1804. }
  1805. else
  1806. {
  1807. soft_pwm_bed = MAX_BED_POWER>>1;
  1808. timer02_set_pwm0(soft_pwm_bed << 1);
  1809. }
  1810. }
  1811. else
  1812. {
  1813. soft_pwm_bed = 0;
  1814. timer02_set_pwm0(soft_pwm_bed << 1);
  1815. WRITE(HEATER_BED_PIN,LOW);
  1816. }
  1817. #else //#ifdef BED_LIMIT_SWITCHING
  1818. // Check if temperature is within the correct band
  1819. if(current < BED_MAXTEMP)
  1820. {
  1821. if(current > target + BED_HYSTERESIS)
  1822. {
  1823. soft_pwm_bed = 0;
  1824. timer02_set_pwm0(soft_pwm_bed << 1);
  1825. }
  1826. else if(current <= target - BED_HYSTERESIS)
  1827. {
  1828. soft_pwm_bed = MAX_BED_POWER>>1;
  1829. timer02_set_pwm0(soft_pwm_bed << 1);
  1830. }
  1831. }
  1832. else
  1833. {
  1834. soft_pwm_bed = 0;
  1835. timer02_set_pwm0(soft_pwm_bed << 1);
  1836. WRITE(HEATER_BED_PIN,LOW);
  1837. }
  1838. #endif //BED_LIMIT_SWITCHING
  1839. if(target==0)
  1840. {
  1841. soft_pwm_bed = 0;
  1842. timer02_set_pwm0(soft_pwm_bed << 1);
  1843. }
  1844. #endif //TEMP_SENSOR_BED
  1845. }
  1846. // ISR-safe temperatures
  1847. static volatile bool adc_values_ready = false;
  1848. float current_temperature_isr[EXTRUDERS];
  1849. int target_temperature_isr[EXTRUDERS];
  1850. float current_temperature_bed_isr;
  1851. int target_temperature_bed_isr;
  1852. #ifdef PINDA_THERMISTOR
  1853. float current_temperature_pinda_isr;
  1854. #endif
  1855. #ifdef AMBIENT_THERMISTOR
  1856. float current_temperature_ambient_isr;
  1857. #endif
  1858. // ISR callback from adc when sampling finished
  1859. void adc_callback()
  1860. {
  1861. current_temperature_raw[0] = adc_values[ADC_PIN_IDX(TEMP_0_PIN)]; //heater
  1862. current_temperature_bed_raw = adc_values[ADC_PIN_IDX(TEMP_BED_PIN)];
  1863. #ifdef PINDA_THERMISTOR
  1864. current_temperature_raw_pinda = adc_values[ADC_PIN_IDX(TEMP_PINDA_PIN)];
  1865. #endif //PINDA_THERMISTOR
  1866. #ifdef AMBIENT_THERMISTOR
  1867. current_temperature_raw_ambient = adc_values[ADC_PIN_IDX(TEMP_AMBIENT_PIN)]; // 5->6
  1868. #endif //AMBIENT_THERMISTOR
  1869. #ifdef VOLT_PWR_PIN
  1870. current_voltage_raw_pwr = adc_values[ADC_PIN_IDX(VOLT_PWR_PIN)];
  1871. #endif
  1872. #ifdef VOLT_BED_PIN
  1873. current_voltage_raw_bed = adc_values[ADC_PIN_IDX(VOLT_BED_PIN)]; // 6->9
  1874. #endif
  1875. #ifdef IR_SENSOR_ANALOG
  1876. current_voltage_raw_IR = adc_values[ADC_PIN_IDX(VOLT_IR_PIN)];
  1877. #endif //IR_SENSOR_ANALOG
  1878. adc_values_ready = true;
  1879. }
  1880. static void setCurrentTemperaturesFromIsr()
  1881. {
  1882. for(uint8_t e=0;e<EXTRUDERS;e++)
  1883. current_temperature[e] = current_temperature_isr[e];
  1884. current_temperature_bed = current_temperature_bed_isr;
  1885. #ifdef PINDA_THERMISTOR
  1886. current_temperature_pinda = current_temperature_pinda_isr;
  1887. #endif
  1888. #ifdef AMBIENT_THERMISTOR
  1889. current_temperature_ambient = current_temperature_ambient_isr;
  1890. #endif
  1891. }
  1892. static void setIsrTargetTemperatures()
  1893. {
  1894. for(uint8_t e=0;e<EXTRUDERS;e++)
  1895. target_temperature_isr[e] = target_temperature[e];
  1896. target_temperature_bed_isr = target_temperature_bed;
  1897. }
  1898. /* Synchronize temperatures:
  1899. - fetch updated values from temp_mgr_isr to current values
  1900. - update target temperatures for temp_mgr_isr regulation *if* no temperature error is set
  1901. This function is blocking: check temp_meas_ready before calling! */
  1902. static void updateTemperatures()
  1903. {
  1904. TempMgrGuard temp_mgr_guard;
  1905. setCurrentTemperaturesFromIsr();
  1906. if(!temp_error_state.v) {
  1907. // refuse to update target temperatures in any error condition!
  1908. setIsrTargetTemperatures();
  1909. }
  1910. temp_meas_ready = false;
  1911. }
  1912. /* Convert raw values into actual temperatures for temp_mgr. The raw values are created in the ADC
  1913. interrupt context, while this function runs from temp_mgr_isr which *is* preemptible as
  1914. analog2temp is relatively slow */
  1915. static void setIsrTemperaturesFromRawValues()
  1916. {
  1917. for(uint8_t e=0;e<EXTRUDERS;e++)
  1918. current_temperature_isr[e] = analog2temp(current_temperature_raw[e], e);
  1919. current_temperature_bed_isr = analog2tempBed(current_temperature_bed_raw);
  1920. #ifdef PINDA_THERMISTOR
  1921. current_temperature_pinda_isr = analog2tempBed(current_temperature_raw_pinda);
  1922. #endif
  1923. #ifdef AMBIENT_THERMISTOR
  1924. current_temperature_ambient_isr = analog2tempAmbient(current_temperature_raw_ambient); //thermistor for ambient is NTCG104LH104JT1 (2000)
  1925. #endif
  1926. temp_meas_ready = true;
  1927. }
  1928. static void temp_mgr_pid()
  1929. {
  1930. for(uint8_t e = 0; e < EXTRUDERS; e++)
  1931. pid_heater(e, current_temperature_isr[e], target_temperature_isr[e]);
  1932. pid_bed(current_temperature_bed_isr, target_temperature_bed_isr);
  1933. }
  1934. static void check_temp_runaway()
  1935. {
  1936. #ifdef TEMP_RUNAWAY_EXTRUDER_HYSTERESIS
  1937. for(uint8_t e = 0; e < EXTRUDERS; e++)
  1938. temp_runaway_check(e+1, target_temperature_isr[e], current_temperature_isr[e], soft_pwm[e], false);
  1939. #endif
  1940. #ifdef TEMP_RUNAWAY_BED_HYSTERESIS
  1941. temp_runaway_check(0, target_temperature_bed_isr, current_temperature_bed_isr, soft_pwm_bed, true);
  1942. #endif
  1943. }
  1944. static void check_temp_raw();
  1945. static void temp_mgr_isr()
  1946. {
  1947. // update *_isr temperatures from raw values for PID regulation
  1948. setIsrTemperaturesFromRawValues();
  1949. // clear the error assertion flag before checking again
  1950. temp_error_state.assert = false;
  1951. check_temp_raw(); // check min/max temp using raw values
  1952. check_temp_runaway(); // classic temperature hysteresis check
  1953. #ifdef TEMP_MODEL
  1954. temp_model::check(); // model-based heater check
  1955. #ifdef TEMP_MODEL_DEBUG
  1956. temp_model::log_isr();
  1957. #endif
  1958. #endif
  1959. // PID regulation
  1960. if (pid_tuning_finished)
  1961. temp_mgr_pid();
  1962. }
  1963. ISR(TIMERx_COMPA_vect)
  1964. {
  1965. // immediately schedule a new conversion
  1966. if(adc_values_ready != true) return;
  1967. adc_values_ready = false;
  1968. adc_start_cycle();
  1969. // run temperature management with interrupts enabled to reduce latency
  1970. DISABLE_TEMP_MGR_INTERRUPT();
  1971. NONATOMIC_BLOCK(NONATOMIC_FORCEOFF) {
  1972. temp_mgr_isr();
  1973. }
  1974. ENABLE_TEMP_MGR_INTERRUPT();
  1975. }
  1976. void disable_heater()
  1977. {
  1978. setAllTargetHotends(0);
  1979. setTargetBed(0);
  1980. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1981. // propagate all values down the chain
  1982. setIsrTargetTemperatures();
  1983. temp_mgr_pid();
  1984. // we can't call soft_pwm_core directly to toggle the pins as it would require removing the inline
  1985. // attribute, so disable each pin individually
  1986. #if defined(HEATER_0_PIN) && HEATER_0_PIN > -1 && EXTRUDERS > 0
  1987. WRITE(HEATER_0_PIN,LOW);
  1988. #endif
  1989. #if defined(HEATER_1_PIN) && HEATER_1_PIN > -1 && EXTRUDERS > 1
  1990. WRITE(HEATER_1_PIN,LOW);
  1991. #endif
  1992. #if defined(HEATER_2_PIN) && HEATER_2_PIN > -1 && EXTRUDERS > 2
  1993. WRITE(HEATER_2_PIN,LOW);
  1994. #endif
  1995. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1996. // TODO: this doesn't take immediate effect!
  1997. timer02_set_pwm0(0);
  1998. bedPWMDisabled = 0;
  1999. #endif
  2000. }
  2001. }
  2002. static void check_min_temp_raw()
  2003. {
  2004. static bool bCheckingOnHeater = false; // state variable, which allows to short no-checking delay (is set, when temperature is (first time) over heaterMintemp)
  2005. static bool bCheckingOnBed = false; // state variable, which allows to short no-checking delay (is set, when temperature is (first time) over bedMintemp)
  2006. static ShortTimer oTimer4minTempHeater;
  2007. static ShortTimer oTimer4minTempBed;
  2008. #ifdef AMBIENT_THERMISTOR
  2009. #ifdef AMBIENT_MINTEMP
  2010. // we need to check ambient temperature
  2011. check_min_temp_ambient();
  2012. #endif
  2013. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  2014. if(current_temperature_raw_ambient>(OVERSAMPLENR*MINTEMP_MINAMBIENT_RAW)) // thermistor is NTC type
  2015. #else
  2016. if(current_temperature_raw_ambient=<(OVERSAMPLENR*MINTEMP_MINAMBIENT_RAW))
  2017. #endif
  2018. {
  2019. // ambient temperature is low
  2020. #endif //AMBIENT_THERMISTOR
  2021. // *** 'common' part of code for MK2.5 & MK3
  2022. // * nozzle checking
  2023. if(target_temperature_isr[active_extruder]>minttemp[active_extruder]) {
  2024. // ~ nozzle heating is on
  2025. bCheckingOnHeater=bCheckingOnHeater||(current_temperature_isr[active_extruder]>(minttemp[active_extruder]+TEMP_HYSTERESIS)); // for eventually delay cutting
  2026. if(oTimer4minTempHeater.expired(HEATER_MINTEMP_DELAY)||(!oTimer4minTempHeater.running())||bCheckingOnHeater) {
  2027. bCheckingOnHeater=true; // not necessary
  2028. check_min_temp_heater0(); // delay is elapsed or temperature is/was over minTemp => periodical checking is active
  2029. }
  2030. }
  2031. else {
  2032. // ~ nozzle heating is off
  2033. oTimer4minTempHeater.start();
  2034. bCheckingOnHeater=false;
  2035. }
  2036. // * bed checking
  2037. if(target_temperature_bed_isr>BED_MINTEMP) {
  2038. // ~ bed heating is on
  2039. bCheckingOnBed=bCheckingOnBed||(current_temperature_bed_isr>(BED_MINTEMP+TEMP_HYSTERESIS)); // for eventually delay cutting
  2040. if(oTimer4minTempBed.expired(BED_MINTEMP_DELAY)||(!oTimer4minTempBed.running())||bCheckingOnBed) {
  2041. bCheckingOnBed=true; // not necessary
  2042. check_min_temp_bed(); // delay is elapsed or temperature is/was over minTemp => periodical checking is active
  2043. }
  2044. }
  2045. else {
  2046. // ~ bed heating is off
  2047. oTimer4minTempBed.start();
  2048. bCheckingOnBed=false;
  2049. }
  2050. // *** end of 'common' part
  2051. #ifdef AMBIENT_THERMISTOR
  2052. }
  2053. else {
  2054. // ambient temperature is standard
  2055. check_min_temp_heater0();
  2056. check_min_temp_bed();
  2057. }
  2058. #endif //AMBIENT_THERMISTOR
  2059. }
  2060. static void check_temp_raw()
  2061. {
  2062. // order is relevant: check_min_temp_raw requires max to be reliable due to
  2063. // ambient temperature being used for low handling temperatures
  2064. check_max_temp_raw();
  2065. check_min_temp_raw();
  2066. }
  2067. #ifdef TEMP_MODEL
  2068. namespace temp_model {
  2069. void model_data::reset(uint8_t heater_pwm _UNUSED, uint8_t fan_pwm _UNUSED,
  2070. float heater_temp _UNUSED, float ambient_temp _UNUSED)
  2071. {
  2072. // pre-compute invariant values
  2073. C_i = (TEMP_MGR_INTV / C);
  2074. warn_s = warn * TEMP_MGR_INTV;
  2075. err_s = err * TEMP_MGR_INTV;
  2076. // initial values
  2077. for(uint8_t i = 0; i != TEMP_MODEL_LAG_SIZE; ++i)
  2078. dT_lag_buf[i] = NAN;
  2079. dT_lag_idx = 0;
  2080. dT_err_prev = 0;
  2081. T_prev = NAN;
  2082. // clear the initialization flag
  2083. flag_bits.uninitialized = false;
  2084. }
  2085. static constexpr float iir_mul(const float a, const float b, const float f, const float nanv)
  2086. {
  2087. const float a_ = !isnan(a) ? a : nanv;
  2088. return (a_ * (1.f - f)) + (b * f);
  2089. }
  2090. void model_data::step(uint8_t heater_pwm, uint8_t fan_pwm, float heater_temp, float ambient_temp)
  2091. {
  2092. constexpr float soft_pwm_inv = 1. / ((1 << 7) - 1);
  2093. // input values
  2094. const float heater_scale = soft_pwm_inv * heater_pwm;
  2095. const float cur_heater_temp = heater_temp;
  2096. const float cur_ambient_temp = ambient_temp + Ta_corr;
  2097. const float cur_R = R[fan_pwm]; // resistance at current fan power (K/W)
  2098. float dP = P * heater_scale; // current power [W]
  2099. float dPl = (cur_heater_temp - cur_ambient_temp) / cur_R; // [W] leakage power
  2100. float dT = (dP - dPl) * C_i; // expected temperature difference (K)
  2101. // filter and lag dT
  2102. uint8_t dT_next_idx = (dT_lag_idx == (TEMP_MODEL_LAG_SIZE - 1) ? 0: dT_lag_idx + 1);
  2103. float dT_lag = dT_lag_buf[dT_next_idx];
  2104. float dT_lag_prev = dT_lag_buf[dT_lag_idx];
  2105. float dT_f = iir_mul(dT_lag_prev, dT, TEMP_MODEL_fS, dT);
  2106. dT_lag_buf[dT_next_idx] = dT_f;
  2107. dT_lag_idx = dT_next_idx;
  2108. // calculate and filter dT_err
  2109. float dT_err = (cur_heater_temp - T_prev) - dT_lag;
  2110. float dT_err_f = iir_mul(dT_err_prev, dT_err, TEMP_MODEL_fE, 0.);
  2111. T_prev = cur_heater_temp;
  2112. dT_err_prev = dT_err_f;
  2113. // check and trigger errors
  2114. flag_bits.error = (fabsf(dT_err_f) > err_s);
  2115. flag_bits.warning = (fabsf(dT_err_f) > warn_s);
  2116. }
  2117. // verify calibration status and trigger a model reset if valid
  2118. void setup()
  2119. {
  2120. if(!calibrated()) enabled = false;
  2121. data.flag_bits.uninitialized = true;
  2122. }
  2123. bool calibrated()
  2124. {
  2125. if(!(data.P >= 0)) return false;
  2126. if(!(data.C >= 0)) return false;
  2127. if(!(data.Ta_corr != NAN)) return false;
  2128. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i) {
  2129. if(!(temp_model::data.R[i] >= 0))
  2130. return false;
  2131. }
  2132. if(!(data.warn != NAN)) return false;
  2133. if(!(data.err != NAN)) return false;
  2134. return true;
  2135. }
  2136. void check()
  2137. {
  2138. if(!enabled) return;
  2139. uint8_t heater_pwm = soft_pwm[0];
  2140. uint8_t fan_pwm = soft_pwm_fan;
  2141. float heater_temp = current_temperature_isr[0];
  2142. float ambient_temp = current_temperature_ambient_isr;
  2143. // check if a reset is required to seed the model: this needs to be done with valid
  2144. // ADC values, so we can't do that directly in init()
  2145. if(data.flag_bits.uninitialized)
  2146. data.reset(heater_pwm, fan_pwm, heater_temp, ambient_temp);
  2147. // step the model
  2148. data.step(heater_pwm, fan_pwm, heater_temp, ambient_temp);
  2149. // handle errors
  2150. if(data.flag_bits.error)
  2151. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::model);
  2152. // handle warning conditions as lower-priority but with greater feedback
  2153. warning_state.assert = data.flag_bits.warning;
  2154. if(warning_state.assert) {
  2155. warning_state.warning = true;
  2156. warning_state.dT_err = temp_model::data.dT_err_prev;
  2157. }
  2158. }
  2159. void handle_warning()
  2160. {
  2161. // update values
  2162. float warn = data.warn;
  2163. float dT_err;
  2164. {
  2165. TempMgrGuard temp_mgr_guard;
  2166. dT_err = warning_state.dT_err;
  2167. }
  2168. dT_err /= TEMP_MGR_INTV; // per-sample => K/s
  2169. printf_P(PSTR("TM: error |%f|>%f\n"), (double)dT_err, (double)warn);
  2170. static bool first = true;
  2171. if(warning_state.assert) {
  2172. if (first) {
  2173. if(warn_beep) {
  2174. lcd_setalertstatuspgm(_T(MSG_THERMAL_ANOMALY), LCD_STATUS_INFO);
  2175. WRITE(BEEPER, HIGH);
  2176. }
  2177. first = false;
  2178. } else {
  2179. if(warn_beep) TOGGLE(BEEPER);
  2180. }
  2181. } else {
  2182. // warning cleared, reset state
  2183. warning_state.warning = false;
  2184. if(warn_beep) WRITE(BEEPER, LOW);
  2185. first = true;
  2186. }
  2187. }
  2188. #ifdef TEMP_MODEL_DEBUG
  2189. void log_usr()
  2190. {
  2191. if(!log_buf.enabled) return;
  2192. uint8_t counter = log_buf.entry.counter;
  2193. if (counter == log_buf.serial) return;
  2194. int8_t delta_ms;
  2195. uint8_t cur_pwm;
  2196. // avoid strict-aliasing warnings
  2197. union { float cur_temp; uint32_t cur_temp_b; };
  2198. union { float cur_amb; uint32_t cur_amb_b; };
  2199. {
  2200. TempMgrGuard temp_mgr_guard;
  2201. delta_ms = log_buf.entry.delta_ms;
  2202. counter = log_buf.entry.counter;
  2203. cur_pwm = log_buf.entry.cur_pwm;
  2204. cur_temp = log_buf.entry.cur_temp;
  2205. cur_amb = log_buf.entry.cur_amb;
  2206. }
  2207. uint8_t d = counter - log_buf.serial;
  2208. log_buf.serial = counter;
  2209. printf_P(PSTR("TML %d %d %x %lx %lx\n"), (unsigned)d - 1, (int)delta_ms + 1,
  2210. (int)cur_pwm, (unsigned long)cur_temp_b, (unsigned long)cur_amb_b);
  2211. }
  2212. void log_isr()
  2213. {
  2214. if(!log_buf.enabled) return;
  2215. uint32_t stamp = _millis();
  2216. uint8_t delta_ms = stamp - log_buf.entry.stamp - (uint32_t)(TEMP_MGR_INTV * 1000);
  2217. log_buf.entry.stamp = stamp;
  2218. ++log_buf.entry.counter;
  2219. log_buf.entry.delta_ms = delta_ms;
  2220. log_buf.entry.cur_pwm = soft_pwm[0];
  2221. log_buf.entry.cur_temp = current_temperature_isr[0];
  2222. log_buf.entry.cur_amb = current_temperature_ambient_isr;
  2223. }
  2224. #endif
  2225. } // namespace temp_model
  2226. static void temp_model_reset_enabled(bool enabled)
  2227. {
  2228. TempMgrGuard temp_mgr_guard;
  2229. temp_model::enabled = enabled;
  2230. temp_model::data.flag_bits.uninitialized = true;
  2231. }
  2232. bool temp_model_enabled()
  2233. {
  2234. return temp_model::enabled;
  2235. }
  2236. void temp_model_set_enabled(bool enabled)
  2237. {
  2238. // set the enabled flag
  2239. {
  2240. TempMgrGuard temp_mgr_guard;
  2241. temp_model::enabled = enabled;
  2242. temp_model::setup();
  2243. }
  2244. // verify that the model has been enabled
  2245. if(enabled && !temp_model::enabled)
  2246. SERIAL_ECHOLNPGM("TM: invalid parameters, cannot enable");
  2247. }
  2248. void temp_model_set_warn_beep(bool enabled)
  2249. {
  2250. temp_model::warn_beep = enabled;
  2251. }
  2252. void temp_model_set_params(float C, float P, float Ta_corr, float warn, float err)
  2253. {
  2254. TempMgrGuard temp_mgr_guard;
  2255. if(!isnan(C) && C > 0) temp_model::data.C = C;
  2256. if(!isnan(P) && P > 0) temp_model::data.P = P;
  2257. if(!isnan(Ta_corr)) temp_model::data.Ta_corr = Ta_corr;
  2258. if(!isnan(err) && err > 0) temp_model::data.err = err;
  2259. if(!isnan(warn) && warn > 0) temp_model::data.warn = warn;
  2260. // ensure warn <= err
  2261. if (temp_model::data.warn > temp_model::data.err)
  2262. temp_model::data.warn = temp_model::data.err;
  2263. temp_model::setup();
  2264. }
  2265. void temp_model_set_resistance(uint8_t index, float R)
  2266. {
  2267. if(index >= TEMP_MODEL_R_SIZE || R <= 0)
  2268. return;
  2269. TempMgrGuard temp_mgr_guard;
  2270. temp_model::data.R[index] = R;
  2271. temp_model::setup();
  2272. }
  2273. void temp_model_report_settings()
  2274. {
  2275. SERIAL_ECHO_START;
  2276. SERIAL_ECHOLNPGM("Temperature Model settings:");
  2277. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2278. printf_P(PSTR("%S M310 I%u R%.2f\n"), echomagic, (unsigned)i, (double)temp_model::data.R[i]);
  2279. printf_P(PSTR("%S M310 P%.2f C%.2f S%u B%u E%.2f W%.2f T%.2f\n"),
  2280. echomagic, (double)temp_model::data.P, (double)temp_model::data.C,
  2281. (unsigned)temp_model::enabled, (unsigned)temp_model::warn_beep,
  2282. (double)temp_model::data.err, (double)temp_model::data.warn,
  2283. (double)temp_model::data.Ta_corr);
  2284. }
  2285. void temp_model_reset_settings()
  2286. {
  2287. TempMgrGuard temp_mgr_guard;
  2288. temp_model::data.P = TEMP_MODEL_P;
  2289. temp_model::data.C = TEMP_MODEL_C;
  2290. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2291. temp_model::data.R[i] = pgm_read_float(TEMP_MODEL_R_DEFAULT + i);
  2292. temp_model::data.Ta_corr = TEMP_MODEL_Ta_corr;
  2293. temp_model::data.warn = TEMP_MODEL_W;
  2294. temp_model::data.err = TEMP_MODEL_E;
  2295. temp_model::warn_beep = true;
  2296. temp_model::enabled = true;
  2297. temp_model::data.flag_bits.uninitialized = true;
  2298. }
  2299. void temp_model_load_settings()
  2300. {
  2301. static_assert(TEMP_MODEL_R_SIZE == 16); // ensure we don't desync with the eeprom table
  2302. TempMgrGuard temp_mgr_guard;
  2303. temp_model::enabled = eeprom_read_byte((uint8_t*)EEPROM_TEMP_MODEL_ENABLE);
  2304. temp_model::data.P = eeprom_read_float((float*)EEPROM_TEMP_MODEL_P);
  2305. temp_model::data.C = eeprom_read_float((float*)EEPROM_TEMP_MODEL_C);
  2306. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2307. temp_model::data.R[i] = eeprom_read_float((float*)EEPROM_TEMP_MODEL_R + i);
  2308. temp_model::data.Ta_corr = eeprom_read_float((float*)EEPROM_TEMP_MODEL_Ta_corr);
  2309. temp_model::data.warn = eeprom_read_float((float*)EEPROM_TEMP_MODEL_W);
  2310. temp_model::data.err = eeprom_read_float((float*)EEPROM_TEMP_MODEL_E);
  2311. if(!temp_model::calibrated()) {
  2312. SERIAL_ECHOLNPGM("TM: stored calibration invalid, resetting");
  2313. temp_model_reset_settings();
  2314. }
  2315. temp_model::setup();
  2316. }
  2317. void temp_model_save_settings()
  2318. {
  2319. eeprom_update_byte((uint8_t*)EEPROM_TEMP_MODEL_ENABLE, temp_model::enabled);
  2320. eeprom_update_float((float*)EEPROM_TEMP_MODEL_P, temp_model::data.P);
  2321. eeprom_update_float((float*)EEPROM_TEMP_MODEL_C, temp_model::data.C);
  2322. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2323. eeprom_update_float((float*)EEPROM_TEMP_MODEL_R + i, temp_model::data.R[i]);
  2324. eeprom_update_float((float*)EEPROM_TEMP_MODEL_Ta_corr, temp_model::data.Ta_corr);
  2325. eeprom_update_float((float*)EEPROM_TEMP_MODEL_W, temp_model::data.warn);
  2326. eeprom_update_float((float*)EEPROM_TEMP_MODEL_E, temp_model::data.err);
  2327. }
  2328. namespace temp_model_cal {
  2329. // set current fan speed for both front/backend
  2330. static __attribute__((noinline)) void set_fan_speed(uint8_t fan_speed)
  2331. {
  2332. #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1)
  2333. // reset the fan measuring state due to missing hysteresis handling on the checking side
  2334. fan_measuring = false;
  2335. extruder_autofan_last_check = _millis();
  2336. #endif
  2337. fanSpeed = fan_speed;
  2338. #ifdef FAN_SOFT_PWM
  2339. fanSpeedSoftPwm = fan_speed;
  2340. #endif
  2341. }
  2342. static void waiting_handler()
  2343. {
  2344. manage_heater();
  2345. host_keepalive();
  2346. host_autoreport();
  2347. checkFans();
  2348. lcd_update(0);
  2349. }
  2350. static void wait(unsigned ms)
  2351. {
  2352. unsigned long mark = _millis() + ms;
  2353. while(_millis() < mark) {
  2354. if(temp_error_state.v) break;
  2355. waiting_handler();
  2356. }
  2357. }
  2358. static void __attribute__((noinline)) wait_temp()
  2359. {
  2360. while(current_temperature[0] < (target_temperature[0] - TEMP_HYSTERESIS)) {
  2361. if(temp_error_state.v) break;
  2362. waiting_handler();
  2363. }
  2364. }
  2365. static void cooldown(float temp)
  2366. {
  2367. uint8_t old_speed = fanSpeed;
  2368. set_fan_speed(255);
  2369. while(current_temperature[0] >= temp) {
  2370. if(temp_error_state.v) break;
  2371. float ambient = current_temperature_ambient + temp_model::data.Ta_corr;
  2372. if(current_temperature[0] < (ambient + TEMP_HYSTERESIS)) {
  2373. // do not get stuck waiting very close to ambient temperature
  2374. break;
  2375. }
  2376. waiting_handler();
  2377. }
  2378. set_fan_speed(old_speed);
  2379. }
  2380. static uint16_t record(uint16_t samples = REC_BUFFER_SIZE) {
  2381. TempMgrGuard temp_mgr_guard;
  2382. uint16_t pos = 0;
  2383. while(pos < samples) {
  2384. if(!TEMP_MGR_INT_FLAG_STATE()) {
  2385. // temperatures not ready yet, just manage heaters while waiting to reduce jitter
  2386. manage_heater();
  2387. continue;
  2388. }
  2389. TEMP_MGR_INT_FLAG_CLEAR();
  2390. // manually repeat what the regular isr would do
  2391. if(adc_values_ready != true) continue;
  2392. adc_values_ready = false;
  2393. adc_start_cycle();
  2394. temp_mgr_isr();
  2395. // stop recording for an hard error condition
  2396. if(temp_error_state.v)
  2397. return 0;
  2398. // record a new entry
  2399. rec_entry& entry = rec_buffer[pos];
  2400. entry.temp = current_temperature_isr[0];
  2401. entry.pwm = soft_pwm[0];
  2402. ++pos;
  2403. // it's now safer to give regular serial/lcd updates a shot
  2404. waiting_handler();
  2405. }
  2406. return pos;
  2407. }
  2408. static float cost_fn(uint16_t samples, float* const var, float v, uint8_t fan_pwm, float ambient)
  2409. {
  2410. *var = v;
  2411. temp_model::data.reset(rec_buffer[0].pwm, fan_pwm, rec_buffer[0].temp, ambient);
  2412. float err = 0;
  2413. uint16_t cnt = 0;
  2414. for(uint16_t i = 1; i < samples; ++i) {
  2415. temp_model::data.step(rec_buffer[i].pwm, fan_pwm, rec_buffer[i].temp, ambient);
  2416. float err_v = temp_model::data.dT_err_prev;
  2417. if(!isnan(err_v)) {
  2418. err += err_v * err_v;
  2419. ++cnt;
  2420. }
  2421. }
  2422. return cnt ? (err / cnt) : NAN;
  2423. }
  2424. constexpr float GOLDEN_RATIO = 0.6180339887498949;
  2425. static void update_section(float points[2], const float bounds[2])
  2426. {
  2427. float d = GOLDEN_RATIO * (bounds[1] - bounds[0]);
  2428. points[0] = bounds[0] + d;
  2429. points[1] = bounds[1] - d;
  2430. }
  2431. static float estimate(uint16_t samples,
  2432. float* const var, float min, float max,
  2433. float thr, uint16_t max_itr,
  2434. uint8_t fan_pwm, float ambient)
  2435. {
  2436. // during estimation we alter the model values without an extra copy to conserve memory
  2437. // so we cannot keep the main checker active until a value has been found
  2438. bool was_enabled = temp_model::enabled;
  2439. temp_model_reset_enabled(false);
  2440. float orig = *var;
  2441. float e = NAN;
  2442. float points[2];
  2443. float bounds[2] = {min, max};
  2444. update_section(points, bounds);
  2445. for(uint8_t it = 0; it != max_itr; ++it) {
  2446. float c1 = cost_fn(samples, var, points[0], fan_pwm, ambient);
  2447. float c2 = cost_fn(samples, var, points[1], fan_pwm, ambient);
  2448. bool dir = (c2 < c1);
  2449. bounds[dir] = points[!dir];
  2450. update_section(points, bounds);
  2451. float x = points[!dir];
  2452. e = (1-GOLDEN_RATIO) * fabsf((bounds[0]-bounds[1]) / x);
  2453. printf_P(PSTR("TM iter:%u v:%.2f e:%.3f\n"), it, x, e);
  2454. if(e < thr) {
  2455. if(x == min || x == max) {
  2456. // real value likely outside of the search boundaries
  2457. break;
  2458. }
  2459. *var = x;
  2460. temp_model_reset_enabled(was_enabled);
  2461. return e;
  2462. }
  2463. }
  2464. SERIAL_ECHOLNPGM("TM estimation did not converge");
  2465. *var = orig;
  2466. temp_model_reset_enabled(was_enabled);
  2467. return NAN;
  2468. }
  2469. static bool autotune(int16_t cal_temp)
  2470. {
  2471. uint16_t samples;
  2472. float e;
  2473. char tm_message[LCD_WIDTH+1];
  2474. // bootstrap C/R values without fan
  2475. set_fan_speed(0);
  2476. for(uint8_t i = 0; i != 2; ++i) {
  2477. const char* PROGMEM verb = (i == 0? PSTR("initial"): PSTR("refine"));
  2478. target_temperature[0] = 0;
  2479. if(current_temperature[0] >= TEMP_MODEL_CAL_Tl) {
  2480. sprintf_P(tm_message, PSTR("TM: cool down <%dC"), TEMP_MODEL_CAL_Tl);
  2481. lcd_setstatus_serial(tm_message);
  2482. cooldown(TEMP_MODEL_CAL_Tl);
  2483. wait(10000);
  2484. }
  2485. sprintf_P(tm_message, PSTR("TM: %S C est."), verb);
  2486. lcd_setstatus_serial(tm_message);
  2487. target_temperature[0] = cal_temp;
  2488. samples = record();
  2489. if(temp_error_state.v || !samples)
  2490. return true;
  2491. // we need a high R value for the initial C guess
  2492. if(isnan(temp_model::data.R[0]))
  2493. temp_model::data.R[0] = TEMP_MODEL_Rh;
  2494. e = estimate(samples, &temp_model::data.C,
  2495. TEMP_MODEL_Cl, TEMP_MODEL_Ch, TEMP_MODEL_C_thr, TEMP_MODEL_C_itr,
  2496. 0, current_temperature_ambient);
  2497. if(isnan(e))
  2498. return true;
  2499. wait_temp();
  2500. if(i) break; // we don't need to refine R
  2501. wait(30000); // settle PID regulation
  2502. sprintf_P(tm_message, PSTR("TM: %S R %dC"), verb, cal_temp);
  2503. lcd_setstatus_serial(tm_message);
  2504. samples = record();
  2505. if(temp_error_state.v || !samples)
  2506. return true;
  2507. e = estimate(samples, &temp_model::data.R[0],
  2508. TEMP_MODEL_Rl, TEMP_MODEL_Rh, TEMP_MODEL_R_thr, TEMP_MODEL_R_itr,
  2509. 0, current_temperature_ambient);
  2510. if(isnan(e))
  2511. return true;
  2512. }
  2513. // Estimate fan losses at regular intervals, starting from full speed to avoid low-speed
  2514. // kickstart issues, although this requires us to wait more for the PID stabilization.
  2515. // Normally exhibits logarithmic behavior with the stock fan+shroud, so the shorter interval
  2516. // at lower speeds is helpful to increase the resolution of the interpolation.
  2517. set_fan_speed(255);
  2518. wait(30000);
  2519. for(int8_t i = TEMP_MODEL_R_SIZE - 1; i > 0; i -= TEMP_MODEL_CAL_R_STEP) {
  2520. // always disable the checker while estimating fan resistance as the difference
  2521. // (esp with 3rd-party blowers) can be massive
  2522. temp_model::data.R[i] = NAN;
  2523. uint8_t speed = 256 / TEMP_MODEL_R_SIZE * (i + 1) - 1;
  2524. set_fan_speed(speed);
  2525. wait(10000);
  2526. sprintf_P(tm_message, PSTR("TM: R[%u] estimat."), (unsigned)i);
  2527. lcd_setstatus_serial(tm_message);
  2528. samples = record();
  2529. if(temp_error_state.v || !samples)
  2530. return true;
  2531. // a fixed fan pwm (the norminal value) is used here, as soft_pwm_fan will be modified
  2532. // during fan measurements and we'd like to include that skew during normal operation.
  2533. e = estimate(samples, &temp_model::data.R[i],
  2534. TEMP_MODEL_Rl, temp_model::data.R[0], TEMP_MODEL_R_thr, TEMP_MODEL_R_itr,
  2535. i, current_temperature_ambient);
  2536. if(isnan(e))
  2537. return true;
  2538. }
  2539. // interpolate remaining steps to speed-up calibration
  2540. // TODO: verify that the sampled values are monotically increasing?
  2541. int8_t next = TEMP_MODEL_R_SIZE - 1;
  2542. for(uint8_t i = TEMP_MODEL_R_SIZE - 2; i != 0; --i) {
  2543. if(!((TEMP_MODEL_R_SIZE - i - 1) % TEMP_MODEL_CAL_R_STEP)) {
  2544. next = i;
  2545. continue;
  2546. }
  2547. int8_t prev = next - TEMP_MODEL_CAL_R_STEP;
  2548. if(prev < 0) prev = 0;
  2549. float f = (float)(i - prev) / TEMP_MODEL_CAL_R_STEP;
  2550. float d = (temp_model::data.R[next] - temp_model::data.R[prev]);
  2551. temp_model::data.R[i] = temp_model::data.R[prev] + d * f;
  2552. }
  2553. return false;
  2554. }
  2555. } // namespace temp_model_cal
  2556. static bool temp_model_autotune_err = true;
  2557. void temp_model_autotune(int16_t temp, bool selftest)
  2558. {
  2559. float orig_C, orig_R[TEMP_MODEL_R_SIZE];
  2560. bool orig_enabled;
  2561. static_assert(sizeof(orig_R) == sizeof(temp_model::data.R));
  2562. // fail-safe error state
  2563. temp_model_autotune_err = true;
  2564. char tm_message[LCD_WIDTH+1];
  2565. if(moves_planned() || printer_active()) {
  2566. sprintf_P(tm_message, PSTR("TM: Cal. NOT IDLE"));
  2567. lcd_setstatus_serial(tm_message);
  2568. return;
  2569. }
  2570. // lockout the printer during calibration
  2571. KEEPALIVE_STATE(IN_PROCESS);
  2572. menu_set_block(MENU_BLOCK_TEMP_MODEL_AUTOTUNE);
  2573. lcd_return_to_status();
  2574. // save the original model data and set the model checking state during self-calibration
  2575. orig_C = temp_model::data.C;
  2576. memcpy(orig_R, temp_model::data.R, sizeof(temp_model::data.R));
  2577. orig_enabled = temp_model::enabled;
  2578. temp_model_reset_enabled(selftest);
  2579. // autotune
  2580. SERIAL_ECHOLNPGM("TM: calibration start");
  2581. temp_model_autotune_err = temp_model_cal::autotune(temp > 0 ? temp : TEMP_MODEL_CAL_Th);
  2582. // always reset temperature
  2583. disable_heater();
  2584. if(temp_model_autotune_err) {
  2585. sprintf_P(tm_message, PSTR("TM: calibr. failed!"));
  2586. lcd_setstatus_serial(tm_message);
  2587. if(temp_error_state.v)
  2588. temp_model_cal::set_fan_speed(255);
  2589. // show calibrated values before overwriting them
  2590. temp_model_report_settings();
  2591. // restore original state
  2592. temp_model::data.C = orig_C;
  2593. memcpy(temp_model::data.R, orig_R, sizeof(temp_model::data.R));
  2594. temp_model_set_enabled(orig_enabled);
  2595. } else {
  2596. lcd_setstatuspgm(MSG_WELCOME);
  2597. temp_model_cal::set_fan_speed(0);
  2598. temp_model_set_enabled(orig_enabled);
  2599. temp_model_report_settings();
  2600. }
  2601. lcd_consume_click();
  2602. menu_unset_block(MENU_BLOCK_TEMP_MODEL_AUTOTUNE);
  2603. }
  2604. bool temp_model_autotune_result()
  2605. {
  2606. return !temp_model_autotune_err;
  2607. }
  2608. #ifdef TEMP_MODEL_DEBUG
  2609. void temp_model_log_enable(bool enable)
  2610. {
  2611. if(enable) {
  2612. TempMgrGuard temp_mgr_guard;
  2613. temp_model::log_buf.entry.stamp = _millis();
  2614. }
  2615. temp_model::log_buf.enabled = enable;
  2616. }
  2617. #endif
  2618. #endif