temperature.cpp 77 KB

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