temperature.cpp 85 KB

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