temperature.cpp 84 KB

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