temperature.cpp 85 KB

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