temperature.cpp 66 KB

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