temperature.cpp 70 KB

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