temperature.cpp 88 KB

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