temperature.cpp 86 KB

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