temperature.cpp 70 KB

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