temperature.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879
  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. 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. void temp_runaway_stop(bool isPreheat, bool isBed)
  859. {
  860. disable_heater();
  861. Sound_MakeCustom(200,0,true);
  862. if (isPreheat)
  863. {
  864. lcd_setalertstatuspgm(isBed? PSTR("BED PREHEAT ERROR") : PSTR("PREHEAT ERROR"), LCD_STATUS_CRITICAL);
  865. SERIAL_ERROR_START;
  866. isBed ? SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HEATBED)") : SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HOTEND)");
  867. hotendFanSetFullSpeed();
  868. }
  869. else
  870. {
  871. lcd_setalertstatuspgm(isBed? PSTR("BED THERMAL RUNAWAY") : PSTR("THERMAL RUNAWAY"), LCD_STATUS_CRITICAL);
  872. SERIAL_ERROR_START;
  873. isBed ? SERIAL_ERRORLNPGM(" HEATBED THERMAL RUNAWAY") : SERIAL_ERRORLNPGM(" HOTEND THERMAL RUNAWAY");
  874. }
  875. Stop();
  876. if (farm_mode) {
  877. prusa_statistics(0);
  878. prusa_statistics(isPreheat? 91 : 90);
  879. }
  880. }
  881. #endif
  882. //! codes of alert messages for the LCD - it is shorter to compare an uin8_t
  883. //! than raw const char * of the messages themselves.
  884. //! Could be used for MAXTEMP situations too - after reaching MAXTEMP and turning off the heater automagically
  885. //! the heater/bed may cool down and a similar alert message like "MAXTERM fixed..." may be displayed.
  886. enum { LCDALERT_NONE = 0, LCDALERT_HEATERMINTEMP, LCDALERT_BEDMINTEMP, LCDALERT_MINTEMPFIXED, LCDALERT_PLEASERESTART };
  887. //! remember the last alert message sent to the LCD
  888. //! to prevent flicker and improve speed
  889. uint8_t last_alert_sent_to_lcd = LCDALERT_NONE;
  890. //! update the current temperature error message
  891. //! @param type short error abbreviation (PROGMEM)
  892. void temp_update_messagepgm(const char* PROGMEM type)
  893. {
  894. char msg[LCD_WIDTH];
  895. strcpy_P(msg, PSTR("Err: "));
  896. strcat_P(msg, type);
  897. lcd_setalertstatus(msg, LCD_STATUS_CRITICAL);
  898. }
  899. //! signal a temperature error on both the lcd and serial
  900. //! @param type short error abbreviation (PROGMEM)
  901. //! @param e optional extruder index for hotend errors
  902. void temp_error_messagepgm(const char* PROGMEM type, uint8_t e = EXTRUDERS)
  903. {
  904. temp_update_messagepgm(type);
  905. SERIAL_ERROR_START;
  906. if(e != EXTRUDERS) {
  907. SERIAL_ERROR((int)e);
  908. SERIAL_ERRORPGM(": ");
  909. }
  910. SERIAL_ERRORPGM("Heaters switched off. ");
  911. SERIAL_ERRORRPGM(type);
  912. SERIAL_ERRORLNPGM(" triggered!");
  913. }
  914. void max_temp_error(uint8_t e) {
  915. disable_heater();
  916. if(IsStopped() == false) {
  917. temp_error_messagepgm(PSTR("MAXTEMP"), e);
  918. }
  919. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  920. Stop();
  921. #endif
  922. hotendFanSetFullSpeed();
  923. if (farm_mode) { prusa_statistics(93); }
  924. }
  925. void min_temp_error(uint8_t e) {
  926. #ifdef DEBUG_DISABLE_MINTEMP
  927. return;
  928. #endif
  929. disable_heater();
  930. //if (current_temperature_ambient < MINTEMP_MINAMBIENT) return;
  931. static const char err[] PROGMEM = "MINTEMP";
  932. if(IsStopped() == false) {
  933. temp_error_messagepgm(err, e);
  934. last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  935. } 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)
  936. // we are already stopped due to some error, only update the status message without flickering
  937. temp_update_messagepgm(err);
  938. last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  939. }
  940. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  941. // if( last_alert_sent_to_lcd != LCDALERT_HEATERMINTEMP ){
  942. // last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  943. // lcd_print_stop();
  944. // }
  945. Stop();
  946. #endif
  947. if (farm_mode) { prusa_statistics(92); }
  948. }
  949. void bed_max_temp_error(void) {
  950. disable_heater();
  951. if(IsStopped() == false) {
  952. temp_error_messagepgm(PSTR("MAXTEMP BED"));
  953. }
  954. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  955. Stop();
  956. #endif
  957. }
  958. void bed_min_temp_error(void) {
  959. #ifdef DEBUG_DISABLE_MINTEMP
  960. return;
  961. #endif
  962. disable_heater();
  963. static const char err[] PROGMEM = "MINTEMP BED";
  964. if(IsStopped() == false) {
  965. temp_error_messagepgm(err);
  966. last_alert_sent_to_lcd = LCDALERT_BEDMINTEMP;
  967. } 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)
  968. // we are already stopped due to some error, only update the status message without flickering
  969. temp_update_messagepgm(err);
  970. last_alert_sent_to_lcd = LCDALERT_BEDMINTEMP;
  971. }
  972. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  973. Stop();
  974. #endif
  975. }
  976. #ifdef AMBIENT_THERMISTOR
  977. void ambient_max_temp_error(void) {
  978. disable_heater();
  979. if(IsStopped() == false) {
  980. temp_error_messagepgm(PSTR("MAXTEMP AMB"));
  981. }
  982. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  983. Stop();
  984. #endif
  985. }
  986. void ambient_min_temp_error(void) {
  987. #ifdef DEBUG_DISABLE_MINTEMP
  988. return;
  989. #endif
  990. disable_heater();
  991. if(IsStopped() == false) {
  992. temp_error_messagepgm(PSTR("MINTEMP AMB"));
  993. }
  994. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  995. Stop();
  996. #endif
  997. }
  998. #endif
  999. #ifdef HEATER_0_USES_MAX6675
  1000. #define MAX6675_HEAT_INTERVAL 250
  1001. long max6675_previous_millis = MAX6675_HEAT_INTERVAL;
  1002. int max6675_temp = 2000;
  1003. int read_max6675()
  1004. {
  1005. if (_millis() - max6675_previous_millis < MAX6675_HEAT_INTERVAL)
  1006. return max6675_temp;
  1007. max6675_previous_millis = _millis();
  1008. max6675_temp = 0;
  1009. #ifdef PRR
  1010. PRR &= ~(1<<PRSPI);
  1011. #elif defined PRR0
  1012. PRR0 &= ~(1<<PRSPI);
  1013. #endif
  1014. SPCR = (1<<MSTR) | (1<<SPE) | (1<<SPR0);
  1015. // enable TT_MAX6675
  1016. WRITE(MAX6675_SS, 0);
  1017. // ensure 100ns delay - a bit extra is fine
  1018. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1019. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1020. // read MSB
  1021. SPDR = 0;
  1022. for (;(SPSR & (1<<SPIF)) == 0;);
  1023. max6675_temp = SPDR;
  1024. max6675_temp <<= 8;
  1025. // read LSB
  1026. SPDR = 0;
  1027. for (;(SPSR & (1<<SPIF)) == 0;);
  1028. max6675_temp |= SPDR;
  1029. // disable TT_MAX6675
  1030. WRITE(MAX6675_SS, 1);
  1031. if (max6675_temp & 4)
  1032. {
  1033. // thermocouple open
  1034. max6675_temp = 2000;
  1035. }
  1036. else
  1037. {
  1038. max6675_temp = max6675_temp >> 3;
  1039. }
  1040. return max6675_temp;
  1041. }
  1042. #endif
  1043. #ifdef BABYSTEPPING
  1044. FORCE_INLINE static void applyBabysteps() {
  1045. for(uint8_t axis=0;axis<3;axis++)
  1046. {
  1047. int curTodo=babystepsTodo[axis]; //get rid of volatile for performance
  1048. if(curTodo>0)
  1049. {
  1050. CRITICAL_SECTION_START;
  1051. babystep(axis,/*fwd*/true);
  1052. babystepsTodo[axis]--; //less to do next time
  1053. CRITICAL_SECTION_END;
  1054. }
  1055. else
  1056. if(curTodo<0)
  1057. {
  1058. CRITICAL_SECTION_START;
  1059. babystep(axis,/*fwd*/false);
  1060. babystepsTodo[axis]++; //less to do next time
  1061. CRITICAL_SECTION_END;
  1062. }
  1063. }
  1064. }
  1065. #endif //BABYSTEPPING
  1066. FORCE_INLINE static void soft_pwm_core()
  1067. {
  1068. static uint8_t pwm_count = (1 << SOFT_PWM_SCALE);
  1069. static uint8_t soft_pwm_0;
  1070. #ifdef SLOW_PWM_HEATERS
  1071. static unsigned char slow_pwm_count = 0;
  1072. static unsigned char state_heater_0 = 0;
  1073. static unsigned char state_timer_heater_0 = 0;
  1074. #endif
  1075. #if (EXTRUDERS > 1) || defined(HEATERS_PARALLEL)
  1076. static unsigned char soft_pwm_1;
  1077. #ifdef SLOW_PWM_HEATERS
  1078. static unsigned char state_heater_1 = 0;
  1079. static unsigned char state_timer_heater_1 = 0;
  1080. #endif
  1081. #endif
  1082. #if EXTRUDERS > 2
  1083. static unsigned char soft_pwm_2;
  1084. #ifdef SLOW_PWM_HEATERS
  1085. static unsigned char state_heater_2 = 0;
  1086. static unsigned char state_timer_heater_2 = 0;
  1087. #endif
  1088. #endif
  1089. #if HEATER_BED_PIN > -1
  1090. // @@DR static unsigned char soft_pwm_b;
  1091. #ifdef SLOW_PWM_HEATERS
  1092. static unsigned char state_heater_b = 0;
  1093. static unsigned char state_timer_heater_b = 0;
  1094. #endif
  1095. #endif
  1096. #if defined(FILWIDTH_PIN) &&(FILWIDTH_PIN > -1)
  1097. static unsigned long raw_filwidth_value = 0; //added for filament width sensor
  1098. #endif
  1099. #ifndef SLOW_PWM_HEATERS
  1100. /*
  1101. * standard PWM modulation
  1102. */
  1103. if (pwm_count == 0)
  1104. {
  1105. soft_pwm_0 = soft_pwm[0];
  1106. if(soft_pwm_0 > 0)
  1107. {
  1108. WRITE(HEATER_0_PIN,1);
  1109. #ifdef HEATERS_PARALLEL
  1110. WRITE(HEATER_1_PIN,1);
  1111. #endif
  1112. } else WRITE(HEATER_0_PIN,0);
  1113. #if EXTRUDERS > 1
  1114. soft_pwm_1 = soft_pwm[1];
  1115. if(soft_pwm_1 > 0) WRITE(HEATER_1_PIN,1); else WRITE(HEATER_1_PIN,0);
  1116. #endif
  1117. #if EXTRUDERS > 2
  1118. soft_pwm_2 = soft_pwm[2];
  1119. if(soft_pwm_2 > 0) WRITE(HEATER_2_PIN,1); else WRITE(HEATER_2_PIN,0);
  1120. #endif
  1121. }
  1122. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1123. #if 0 // @@DR vypnuto pro hw pwm bedu
  1124. // tuhle prasarnu bude potreba poustet ve stanovenych intervalech, jinak nemam moc sanci zareagovat
  1125. // teoreticky by se tato cast uz vubec nemusela poustet
  1126. if ((pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1)) == 0)
  1127. {
  1128. soft_pwm_b = soft_pwm_bed >> (7 - HEATER_BED_SOFT_PWM_BITS);
  1129. # ifndef SYSTEM_TIMER_2
  1130. // tady budu krokovat pomalou frekvenci na automatu - tohle je rizeni spinani a rozepinani
  1131. // jako ridici frekvenci mam 2khz, jako vystupni frekvenci mam 30hz
  1132. // 2kHz jsou ovsem ve slysitelnem pasmu, mozna bude potreba jit s frekvenci nahoru (a tomu taky prizpusobit ostatni veci)
  1133. // Teoreticky bych mohl stahnout OCR0B citac na 6, cimz bych se dostal nekam ke 40khz a tady potom honit PWM rychleji nebo i pomaleji
  1134. // to nicemu nevadi. Soft PWM scale by se 20x zvetsilo (no dobre, 16x), cimz by se to posunulo k puvodnimu 30Hz PWM
  1135. //if(soft_pwm_b > 0) WRITE(HEATER_BED_PIN,1); else WRITE(HEATER_BED_PIN,0);
  1136. # endif //SYSTEM_TIMER_2
  1137. }
  1138. #endif
  1139. #endif
  1140. #ifdef FAN_SOFT_PWM
  1141. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1142. {
  1143. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1144. if(soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1145. }
  1146. #endif
  1147. if(soft_pwm_0 < pwm_count)
  1148. {
  1149. WRITE(HEATER_0_PIN,0);
  1150. #ifdef HEATERS_PARALLEL
  1151. WRITE(HEATER_1_PIN,0);
  1152. #endif
  1153. }
  1154. #if EXTRUDERS > 1
  1155. if(soft_pwm_1 < pwm_count) WRITE(HEATER_1_PIN,0);
  1156. #endif
  1157. #if EXTRUDERS > 2
  1158. if(soft_pwm_2 < pwm_count) WRITE(HEATER_2_PIN,0);
  1159. #endif
  1160. #if 0 // @@DR
  1161. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1162. if (soft_pwm_b < (pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1))){
  1163. //WRITE(HEATER_BED_PIN,0);
  1164. }
  1165. //WRITE(HEATER_BED_PIN, pwm_count & 1 );
  1166. #endif
  1167. #endif
  1168. #ifdef FAN_SOFT_PWM
  1169. if (soft_pwm_fan < (pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1))) WRITE(FAN_PIN,0);
  1170. #endif
  1171. pwm_count += (1 << SOFT_PWM_SCALE);
  1172. pwm_count &= 0x7f;
  1173. #else //ifndef SLOW_PWM_HEATERS
  1174. /*
  1175. * SLOW PWM HEATERS
  1176. *
  1177. * for heaters drived by relay
  1178. */
  1179. #ifndef MIN_STATE_TIME
  1180. #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
  1181. #endif
  1182. if (slow_pwm_count == 0) {
  1183. // EXTRUDER 0
  1184. soft_pwm_0 = soft_pwm[0];
  1185. if (soft_pwm_0 > 0) {
  1186. // turn ON heather only if the minimum time is up
  1187. if (state_timer_heater_0 == 0) {
  1188. // if change state set timer
  1189. if (state_heater_0 == 0) {
  1190. state_timer_heater_0 = MIN_STATE_TIME;
  1191. }
  1192. state_heater_0 = 1;
  1193. WRITE(HEATER_0_PIN, 1);
  1194. #ifdef HEATERS_PARALLEL
  1195. WRITE(HEATER_1_PIN, 1);
  1196. #endif
  1197. }
  1198. } else {
  1199. // turn OFF heather only if the minimum time is up
  1200. if (state_timer_heater_0 == 0) {
  1201. // if change state set timer
  1202. if (state_heater_0 == 1) {
  1203. state_timer_heater_0 = MIN_STATE_TIME;
  1204. }
  1205. state_heater_0 = 0;
  1206. WRITE(HEATER_0_PIN, 0);
  1207. #ifdef HEATERS_PARALLEL
  1208. WRITE(HEATER_1_PIN, 0);
  1209. #endif
  1210. }
  1211. }
  1212. #if EXTRUDERS > 1
  1213. // EXTRUDER 1
  1214. soft_pwm_1 = soft_pwm[1];
  1215. if (soft_pwm_1 > 0) {
  1216. // turn ON heather only if the minimum time is up
  1217. if (state_timer_heater_1 == 0) {
  1218. // if change state set timer
  1219. if (state_heater_1 == 0) {
  1220. state_timer_heater_1 = MIN_STATE_TIME;
  1221. }
  1222. state_heater_1 = 1;
  1223. WRITE(HEATER_1_PIN, 1);
  1224. }
  1225. } else {
  1226. // turn OFF heather only if the minimum time is up
  1227. if (state_timer_heater_1 == 0) {
  1228. // if change state set timer
  1229. if (state_heater_1 == 1) {
  1230. state_timer_heater_1 = MIN_STATE_TIME;
  1231. }
  1232. state_heater_1 = 0;
  1233. WRITE(HEATER_1_PIN, 0);
  1234. }
  1235. }
  1236. #endif
  1237. #if EXTRUDERS > 2
  1238. // EXTRUDER 2
  1239. soft_pwm_2 = soft_pwm[2];
  1240. if (soft_pwm_2 > 0) {
  1241. // turn ON heather only if the minimum time is up
  1242. if (state_timer_heater_2 == 0) {
  1243. // if change state set timer
  1244. if (state_heater_2 == 0) {
  1245. state_timer_heater_2 = MIN_STATE_TIME;
  1246. }
  1247. state_heater_2 = 1;
  1248. WRITE(HEATER_2_PIN, 1);
  1249. }
  1250. } else {
  1251. // turn OFF heather only if the minimum time is up
  1252. if (state_timer_heater_2 == 0) {
  1253. // if change state set timer
  1254. if (state_heater_2 == 1) {
  1255. state_timer_heater_2 = MIN_STATE_TIME;
  1256. }
  1257. state_heater_2 = 0;
  1258. WRITE(HEATER_2_PIN, 0);
  1259. }
  1260. }
  1261. #endif
  1262. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1263. // BED
  1264. soft_pwm_b = soft_pwm_bed;
  1265. if (soft_pwm_b > 0) {
  1266. // turn ON heather only if the minimum time is up
  1267. if (state_timer_heater_b == 0) {
  1268. // if change state set timer
  1269. if (state_heater_b == 0) {
  1270. state_timer_heater_b = MIN_STATE_TIME;
  1271. }
  1272. state_heater_b = 1;
  1273. //WRITE(HEATER_BED_PIN, 1);
  1274. }
  1275. } else {
  1276. // turn OFF heather only if the minimum time is up
  1277. if (state_timer_heater_b == 0) {
  1278. // if change state set timer
  1279. if (state_heater_b == 1) {
  1280. state_timer_heater_b = MIN_STATE_TIME;
  1281. }
  1282. state_heater_b = 0;
  1283. WRITE(HEATER_BED_PIN, 0);
  1284. }
  1285. }
  1286. #endif
  1287. } // if (slow_pwm_count == 0)
  1288. // EXTRUDER 0
  1289. if (soft_pwm_0 < slow_pwm_count) {
  1290. // turn OFF heather only if the minimum time is up
  1291. if (state_timer_heater_0 == 0) {
  1292. // if change state set timer
  1293. if (state_heater_0 == 1) {
  1294. state_timer_heater_0 = MIN_STATE_TIME;
  1295. }
  1296. state_heater_0 = 0;
  1297. WRITE(HEATER_0_PIN, 0);
  1298. #ifdef HEATERS_PARALLEL
  1299. WRITE(HEATER_1_PIN, 0);
  1300. #endif
  1301. }
  1302. }
  1303. #if EXTRUDERS > 1
  1304. // EXTRUDER 1
  1305. if (soft_pwm_1 < slow_pwm_count) {
  1306. // turn OFF heather only if the minimum time is up
  1307. if (state_timer_heater_1 == 0) {
  1308. // if change state set timer
  1309. if (state_heater_1 == 1) {
  1310. state_timer_heater_1 = MIN_STATE_TIME;
  1311. }
  1312. state_heater_1 = 0;
  1313. WRITE(HEATER_1_PIN, 0);
  1314. }
  1315. }
  1316. #endif
  1317. #if EXTRUDERS > 2
  1318. // EXTRUDER 2
  1319. if (soft_pwm_2 < slow_pwm_count) {
  1320. // turn OFF heather only if the minimum time is up
  1321. if (state_timer_heater_2 == 0) {
  1322. // if change state set timer
  1323. if (state_heater_2 == 1) {
  1324. state_timer_heater_2 = MIN_STATE_TIME;
  1325. }
  1326. state_heater_2 = 0;
  1327. WRITE(HEATER_2_PIN, 0);
  1328. }
  1329. }
  1330. #endif
  1331. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1332. // BED
  1333. if (soft_pwm_b < slow_pwm_count) {
  1334. // turn OFF heather only if the minimum time is up
  1335. if (state_timer_heater_b == 0) {
  1336. // if change state set timer
  1337. if (state_heater_b == 1) {
  1338. state_timer_heater_b = MIN_STATE_TIME;
  1339. }
  1340. state_heater_b = 0;
  1341. WRITE(HEATER_BED_PIN, 0);
  1342. }
  1343. }
  1344. #endif
  1345. #ifdef FAN_SOFT_PWM
  1346. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1347. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1348. if (soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1349. }
  1350. if (soft_pwm_fan < pwm_count) WRITE(FAN_PIN,0);
  1351. #endif
  1352. pwm_count += (1 << SOFT_PWM_SCALE);
  1353. pwm_count &= 0x7f;
  1354. // increment slow_pwm_count only every 64 pwm_count circa 65.5ms
  1355. if ((pwm_count % 64) == 0) {
  1356. slow_pwm_count++;
  1357. slow_pwm_count &= 0x7f;
  1358. // Extruder 0
  1359. if (state_timer_heater_0 > 0) {
  1360. state_timer_heater_0--;
  1361. }
  1362. #if EXTRUDERS > 1
  1363. // Extruder 1
  1364. if (state_timer_heater_1 > 0)
  1365. state_timer_heater_1--;
  1366. #endif
  1367. #if EXTRUDERS > 2
  1368. // Extruder 2
  1369. if (state_timer_heater_2 > 0)
  1370. state_timer_heater_2--;
  1371. #endif
  1372. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1373. // Bed
  1374. if (state_timer_heater_b > 0)
  1375. state_timer_heater_b--;
  1376. #endif
  1377. } //if ((pwm_count % 64) == 0) {
  1378. #endif //ifndef SLOW_PWM_HEATERS
  1379. }
  1380. FORCE_INLINE static void soft_pwm_isr()
  1381. {
  1382. lcd_buttons_update();
  1383. soft_pwm_core();
  1384. #ifdef BABYSTEPPING
  1385. applyBabysteps();
  1386. #endif //BABYSTEPPING
  1387. // Check if a stack overflow happened
  1388. if (!SdFatUtil::test_stack_integrity()) stack_error();
  1389. #if (defined(FANCHECK) && defined(TACH_0) && (TACH_0 > -1))
  1390. readFanTach();
  1391. #endif //(defined(TACH_0))
  1392. }
  1393. // Timer2 (originaly timer0) is shared with millies
  1394. #ifdef SYSTEM_TIMER_2
  1395. ISR(TIMER2_COMPB_vect)
  1396. #else //SYSTEM_TIMER_2
  1397. ISR(TIMER0_COMPB_vect)
  1398. #endif //SYSTEM_TIMER_2
  1399. {
  1400. DISABLE_SOFT_PWM_INTERRUPT();
  1401. sei();
  1402. soft_pwm_isr();
  1403. cli();
  1404. ENABLE_SOFT_PWM_INTERRUPT();
  1405. }
  1406. void check_max_temp_raw()
  1407. {
  1408. //heater
  1409. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1410. if (current_temperature_raw[0] <= maxttemp_raw[0]) {
  1411. #else
  1412. if (current_temperature_raw[0] >= maxttemp_raw[0]) {
  1413. #endif
  1414. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::max);
  1415. }
  1416. //bed
  1417. #if defined(BED_MAXTEMP) && (TEMP_SENSOR_BED != 0)
  1418. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1419. if (current_temperature_bed_raw <= bed_maxttemp_raw) {
  1420. #else
  1421. if (current_temperature_bed_raw >= bed_maxttemp_raw) {
  1422. #endif
  1423. set_temp_error(TempErrorSource::bed, 0, TempErrorType::max);
  1424. }
  1425. #endif
  1426. //ambient
  1427. #if defined(AMBIENT_MAXTEMP) && (TEMP_SENSOR_AMBIENT != 0)
  1428. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1429. if (current_temperature_raw_ambient <= ambient_maxttemp_raw) {
  1430. #else
  1431. if (current_temperature_raw_ambient >= ambient_maxttemp_raw) {
  1432. #endif
  1433. set_temp_error(TempErrorSource::ambient, 0, TempErrorType::max);
  1434. }
  1435. #endif
  1436. }
  1437. //! number of repeating the same state with consecutive step() calls
  1438. //! used to slow down text switching
  1439. struct alert_automaton_mintemp {
  1440. const char *m2;
  1441. alert_automaton_mintemp(const char *m2):m2(m2){}
  1442. private:
  1443. enum { ALERT_AUTOMATON_SPEED_DIV = 5 };
  1444. enum class States : uint8_t { Init = 0, TempAboveMintemp, ShowPleaseRestart, ShowMintemp };
  1445. States state = States::Init;
  1446. uint8_t repeat = ALERT_AUTOMATON_SPEED_DIV;
  1447. void substep(States next_state){
  1448. if( repeat == 0 ){
  1449. state = next_state; // advance to the next state
  1450. repeat = ALERT_AUTOMATON_SPEED_DIV; // and prepare repeating for it too
  1451. } else {
  1452. --repeat;
  1453. }
  1454. }
  1455. public:
  1456. //! brief state automaton step routine
  1457. //! @param current_temp current hotend/bed temperature (for computing simple hysteresis)
  1458. //! @param mintemp minimal temperature including hysteresis to check current_temp against
  1459. void step(float current_temp, float mintemp){
  1460. static const char m1[] PROGMEM = "Please restart";
  1461. switch(state){
  1462. case States::Init: // initial state - check hysteresis
  1463. if( current_temp > mintemp ){
  1464. state = States::TempAboveMintemp;
  1465. }
  1466. // otherwise keep the Err MINTEMP alert message on the display,
  1467. // i.e. do not transfer to state 1
  1468. break;
  1469. case States::TempAboveMintemp: // the temperature has risen above the hysteresis check
  1470. lcd_setalertstatuspgm(m2);
  1471. substep(States::ShowMintemp);
  1472. last_alert_sent_to_lcd = LCDALERT_MINTEMPFIXED;
  1473. break;
  1474. case States::ShowPleaseRestart: // displaying "Please restart"
  1475. lcd_updatestatuspgm(m1);
  1476. substep(States::ShowMintemp);
  1477. last_alert_sent_to_lcd = LCDALERT_PLEASERESTART;
  1478. break;
  1479. case States::ShowMintemp: // displaying "MINTEMP fixed"
  1480. lcd_updatestatuspgm(m2);
  1481. substep(States::ShowPleaseRestart);
  1482. last_alert_sent_to_lcd = LCDALERT_MINTEMPFIXED;
  1483. break;
  1484. }
  1485. }
  1486. };
  1487. static const char m2hotend[] PROGMEM = "MINTEMP HOTEND fixed";
  1488. static const char m2bed[] PROGMEM = "MINTEMP BED fixed";
  1489. static alert_automaton_mintemp alert_automaton_hotend(m2hotend), alert_automaton_bed(m2bed);
  1490. void check_min_temp_heater0()
  1491. {
  1492. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1493. if (current_temperature_raw[0] >= minttemp_raw[0]) {
  1494. #else
  1495. if (current_temperature_raw[0] <= minttemp_raw[0]) {
  1496. #endif
  1497. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::min);
  1498. }
  1499. }
  1500. void check_min_temp_bed()
  1501. {
  1502. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1503. if (current_temperature_bed_raw >= bed_minttemp_raw) {
  1504. #else
  1505. if (current_temperature_bed_raw <= bed_minttemp_raw) {
  1506. #endif
  1507. set_temp_error(TempErrorSource::bed, 0, TempErrorType::min);
  1508. }
  1509. }
  1510. #ifdef AMBIENT_MINTEMP
  1511. void check_min_temp_ambient()
  1512. {
  1513. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1514. if (current_temperature_raw_ambient >= ambient_minttemp_raw) {
  1515. #else
  1516. if (current_temperature_raw_ambient <= ambient_minttemp_raw) {
  1517. #endif
  1518. set_temp_error(TempErrorSource::ambient, 0, TempErrorType::min);
  1519. }
  1520. }
  1521. #endif
  1522. void handle_temp_error()
  1523. {
  1524. // TODO: Stop and the various *_error() functions need an overhaul!
  1525. // The heaters are kept disabled already at a higher level, making almost
  1526. // all the code inside the invidual handlers useless!
  1527. // relay to the original handler
  1528. switch((TempErrorType)temp_error_state.type) {
  1529. case TempErrorType::min:
  1530. switch((TempErrorSource)temp_error_state.source) {
  1531. case TempErrorSource::hotend:
  1532. if(temp_error_state.assert) {
  1533. menu_set_serious_error(SERIOUS_ERR_MINTEMP_HEATER);
  1534. min_temp_error(temp_error_state.index);
  1535. } else if( menu_is_serious_error(SERIOUS_ERR_MINTEMP_HEATER) ) {
  1536. // no recovery, just force the user to restart the printer
  1537. // which is a safer variant than just continuing printing
  1538. // The automaton also checks for hysteresis - the temperature must have reached a few degrees above the MINTEMP, before
  1539. // we shall signalize, that MINTEMP has been fixed
  1540. // Code notice: normally the alert_automaton instance would have been placed here
  1541. // as static alert_automaton_mintemp alert_automaton_hotend, but
  1542. alert_automaton_hotend.step(current_temperature[0], minttemp[0] + TEMP_HYSTERESIS);
  1543. }
  1544. break;
  1545. case TempErrorSource::bed:
  1546. if(temp_error_state.assert) {
  1547. menu_set_serious_error(SERIOUS_ERR_MINTEMP_BED);
  1548. bed_min_temp_error();
  1549. } else if( menu_is_serious_error(SERIOUS_ERR_MINTEMP_BED) ){
  1550. // no recovery, just force the user to restart the printer
  1551. // which is a safer variant than just continuing printing
  1552. alert_automaton_bed.step(current_temperature_bed, BED_MINTEMP + TEMP_HYSTERESIS);
  1553. }
  1554. break;
  1555. case TempErrorSource::ambient:
  1556. ambient_min_temp_error();
  1557. break;
  1558. }
  1559. break;
  1560. case TempErrorType::max:
  1561. switch((TempErrorSource)temp_error_state.source) {
  1562. case TempErrorSource::hotend:
  1563. max_temp_error(temp_error_state.index);
  1564. break;
  1565. case TempErrorSource::bed:
  1566. bed_max_temp_error();
  1567. break;
  1568. case TempErrorSource::ambient:
  1569. ambient_max_temp_error();
  1570. break;
  1571. }
  1572. break;
  1573. case TempErrorType::preheat:
  1574. case TempErrorType::runaway:
  1575. switch((TempErrorSource)temp_error_state.source) {
  1576. case TempErrorSource::hotend:
  1577. case TempErrorSource::bed:
  1578. temp_runaway_stop(
  1579. ((TempErrorType)temp_error_state.type == TempErrorType::preheat),
  1580. ((TempErrorSource)temp_error_state.source == TempErrorSource::bed));
  1581. break;
  1582. case TempErrorSource::ambient:
  1583. // not needed
  1584. break;
  1585. }
  1586. break;
  1587. #ifdef TEMP_MODEL
  1588. case TempErrorType::model:
  1589. if(temp_error_state.assert) {
  1590. // TODO: do something meaningful
  1591. SERIAL_ECHOLNPGM("TM: error triggered!");
  1592. WRITE(BEEPER, HIGH);
  1593. } else {
  1594. temp_error_state.v = 0;
  1595. WRITE(BEEPER, LOW);
  1596. SERIAL_ECHOLNPGM("TM: error cleared");
  1597. }
  1598. break;
  1599. #endif
  1600. }
  1601. }
  1602. #ifdef PIDTEMP
  1603. // Apply the scale factors to the PID values
  1604. float scalePID_i(float i)
  1605. {
  1606. return i*PID_dT;
  1607. }
  1608. float unscalePID_i(float i)
  1609. {
  1610. return i/PID_dT;
  1611. }
  1612. float scalePID_d(float d)
  1613. {
  1614. return d/PID_dT;
  1615. }
  1616. float unscalePID_d(float d)
  1617. {
  1618. return d*PID_dT;
  1619. }
  1620. #endif //PIDTEMP
  1621. #ifdef PINDA_THERMISTOR
  1622. //! @brief PINDA thermistor detected
  1623. //!
  1624. //! @retval true firmware should do temperature compensation and allow calibration
  1625. //! @retval false PINDA thermistor is not detected, disable temperature compensation and calibration
  1626. //! @retval true/false when forced via LCD menu Settings->HW Setup->SuperPINDA
  1627. //!
  1628. bool has_temperature_compensation()
  1629. {
  1630. #ifdef SUPERPINDA_SUPPORT
  1631. #ifdef PINDA_TEMP_COMP
  1632. uint8_t pinda_temp_compensation = eeprom_read_byte((uint8_t*)EEPROM_PINDA_TEMP_COMPENSATION);
  1633. if (pinda_temp_compensation == EEPROM_EMPTY_VALUE) //Unkown PINDA temp compenstation, so check it.
  1634. {
  1635. #endif //PINDA_TEMP_COMP
  1636. return (current_temperature_pinda >= PINDA_MINTEMP) ? true : false;
  1637. #ifdef PINDA_TEMP_COMP
  1638. }
  1639. else if (pinda_temp_compensation == 0) return true; //Overwritten via LCD menu SuperPINDA [No]
  1640. else return false; //Overwritten via LCD menu SuperPINDA [YES]
  1641. #endif //PINDA_TEMP_COMP
  1642. #else
  1643. return true;
  1644. #endif
  1645. }
  1646. #endif //PINDA_THERMISTOR
  1647. // RAII helper class to run a code block with temp_mgr_isr disabled
  1648. class TempMgrGuard
  1649. {
  1650. bool temp_mgr_state;
  1651. public:
  1652. TempMgrGuard() {
  1653. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1654. temp_mgr_state = TEMP_MGR_INTERRUPT_STATE();
  1655. DISABLE_TEMP_MGR_INTERRUPT();
  1656. }
  1657. }
  1658. ~TempMgrGuard() throw() {
  1659. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  1660. if(temp_mgr_state) ENABLE_TEMP_MGR_INTERRUPT();
  1661. }
  1662. }
  1663. };
  1664. void temp_mgr_init()
  1665. {
  1666. // initialize the ADC and start a conversion
  1667. adc_init();
  1668. adc_start_cycle();
  1669. // initialize timer5
  1670. CRITICAL_SECTION_START;
  1671. // CTC
  1672. TCCR5B &= ~(1<<WGM53);
  1673. TCCR5B |= (1<<WGM52);
  1674. TCCR5A &= ~(1<<WGM51);
  1675. TCCR5A &= ~(1<<WGM50);
  1676. // output mode = 00 (disconnected)
  1677. TCCR5A &= ~(3<<COM5A0);
  1678. TCCR5A &= ~(3<<COM5B0);
  1679. // x/256 prescaler
  1680. TCCR5B |= (1<<CS52);
  1681. TCCR5B &= ~(1<<CS51);
  1682. TCCR5B &= ~(1<<CS50);
  1683. // reset counter
  1684. TCNT5 = 0;
  1685. OCR5A = TIMER5_OCRA_OVF;
  1686. // clear pending interrupts, enable COMPA
  1687. TEMP_MGR_INT_FLAG_CLEAR();
  1688. ENABLE_TEMP_MGR_INTERRUPT();
  1689. CRITICAL_SECTION_END;
  1690. }
  1691. static void pid_heater(uint8_t e, const float current, const int target)
  1692. {
  1693. float pid_input;
  1694. float pid_output;
  1695. #ifdef PIDTEMP
  1696. pid_input = current;
  1697. #ifndef PID_OPENLOOP
  1698. if(target == 0) {
  1699. pid_output = 0;
  1700. pid_reset[e] = true;
  1701. } else {
  1702. pid_error[e] = target - pid_input;
  1703. if(pid_reset[e]) {
  1704. iState_sum[e] = 0.0;
  1705. dTerm[e] = 0.0; // 'dState_last[e]' initial setting is not necessary (see end of if-statement)
  1706. pid_reset[e] = false;
  1707. }
  1708. #ifndef PonM
  1709. pTerm[e] = cs.Kp * pid_error[e];
  1710. iState_sum[e] += pid_error[e];
  1711. iState_sum[e] = constrain(iState_sum[e], iState_sum_min[e], iState_sum_max[e]);
  1712. iTerm[e] = cs.Ki * iState_sum[e];
  1713. // PID_K1 defined in Configuration.h in the PID settings
  1714. #define K2 (1.0-PID_K1)
  1715. dTerm[e] = (cs.Kd * (pid_input - dState_last[e]))*K2 + (PID_K1 * dTerm[e]); // e.g. digital filtration of derivative term changes
  1716. 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)
  1717. if (pid_output > PID_MAX) {
  1718. if (pid_error[e] > 0 ) iState_sum[e] -= pid_error[e]; // conditional un-integration
  1719. pid_output=PID_MAX;
  1720. } else if (pid_output < 0) {
  1721. if (pid_error[e] < 0 ) iState_sum[e] -= pid_error[e]; // conditional un-integration
  1722. pid_output=0;
  1723. }
  1724. #else // PonM ("Proportional on Measurement" method)
  1725. iState_sum[e] += cs.Ki * pid_error[e];
  1726. iState_sum[e] -= cs.Kp * (pid_input - dState_last[e]);
  1727. iState_sum[e] = constrain(iState_sum[e], 0, PID_INTEGRAL_DRIVE_MAX);
  1728. dTerm[e] = cs.Kd * (pid_input - dState_last[e]);
  1729. 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)
  1730. pid_output = constrain(pid_output, 0, PID_MAX);
  1731. #endif // PonM
  1732. }
  1733. dState_last[e] = pid_input;
  1734. #else //PID_OPENLOOP
  1735. pid_output = constrain(target[e], 0, PID_MAX);
  1736. #endif //PID_OPENLOOP
  1737. #ifdef PID_DEBUG
  1738. SERIAL_ECHO_START;
  1739. SERIAL_ECHO(" PID_DEBUG ");
  1740. SERIAL_ECHO(e);
  1741. SERIAL_ECHO(": Input ");
  1742. SERIAL_ECHO(pid_input);
  1743. SERIAL_ECHO(" Output ");
  1744. SERIAL_ECHO(pid_output);
  1745. SERIAL_ECHO(" pTerm ");
  1746. SERIAL_ECHO(pTerm[e]);
  1747. SERIAL_ECHO(" iTerm ");
  1748. SERIAL_ECHO(iTerm[e]);
  1749. SERIAL_ECHO(" dTerm ");
  1750. SERIAL_ECHOLN(-dTerm[e]);
  1751. #endif //PID_DEBUG
  1752. #else /* PID off */
  1753. pid_output = 0;
  1754. if(current[e] < target[e]) {
  1755. pid_output = PID_MAX;
  1756. }
  1757. #endif
  1758. // Check if temperature is within the correct range
  1759. if((current < maxttemp[e]) && (target != 0))
  1760. soft_pwm[e] = (int)pid_output >> 1;
  1761. else
  1762. soft_pwm[e] = 0;
  1763. }
  1764. static void pid_bed(const float current, const int target)
  1765. {
  1766. float pid_input;
  1767. float pid_output;
  1768. #ifndef PIDTEMPBED
  1769. if(_millis() - previous_millis_bed_heater < BED_CHECK_INTERVAL)
  1770. return;
  1771. previous_millis_bed_heater = _millis();
  1772. #endif
  1773. #if TEMP_SENSOR_BED != 0
  1774. #ifdef PIDTEMPBED
  1775. pid_input = current;
  1776. #ifndef PID_OPENLOOP
  1777. pid_error_bed = target - pid_input;
  1778. pTerm_bed = cs.bedKp * pid_error_bed;
  1779. temp_iState_bed += pid_error_bed;
  1780. temp_iState_bed = constrain(temp_iState_bed, temp_iState_min_bed, temp_iState_max_bed);
  1781. iTerm_bed = cs.bedKi * temp_iState_bed;
  1782. //PID_K1 defined in Configuration.h in the PID settings
  1783. #define K2 (1.0-PID_K1)
  1784. dTerm_bed= (cs.bedKd * (pid_input - temp_dState_bed))*K2 + (PID_K1 * dTerm_bed);
  1785. temp_dState_bed = pid_input;
  1786. pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
  1787. if (pid_output > MAX_BED_POWER) {
  1788. if (pid_error_bed > 0 ) temp_iState_bed -= pid_error_bed; // conditional un-integration
  1789. pid_output=MAX_BED_POWER;
  1790. } else if (pid_output < 0){
  1791. if (pid_error_bed < 0 ) temp_iState_bed -= pid_error_bed; // conditional un-integration
  1792. pid_output=0;
  1793. }
  1794. #else
  1795. pid_output = constrain(target, 0, MAX_BED_POWER);
  1796. #endif //PID_OPENLOOP
  1797. if(current < BED_MAXTEMP)
  1798. {
  1799. soft_pwm_bed = (int)pid_output >> 1;
  1800. timer02_set_pwm0(soft_pwm_bed << 1);
  1801. }
  1802. else
  1803. {
  1804. soft_pwm_bed = 0;
  1805. timer02_set_pwm0(soft_pwm_bed << 1);
  1806. }
  1807. #elif !defined(BED_LIMIT_SWITCHING)
  1808. // Check if temperature is within the correct range
  1809. if(current < BED_MAXTEMP)
  1810. {
  1811. if(current >= target)
  1812. {
  1813. soft_pwm_bed = 0;
  1814. timer02_set_pwm0(soft_pwm_bed << 1);
  1815. }
  1816. else
  1817. {
  1818. soft_pwm_bed = MAX_BED_POWER>>1;
  1819. timer02_set_pwm0(soft_pwm_bed << 1);
  1820. }
  1821. }
  1822. else
  1823. {
  1824. soft_pwm_bed = 0;
  1825. timer02_set_pwm0(soft_pwm_bed << 1);
  1826. WRITE(HEATER_BED_PIN,LOW);
  1827. }
  1828. #else //#ifdef BED_LIMIT_SWITCHING
  1829. // Check if temperature is within the correct band
  1830. if(current < BED_MAXTEMP)
  1831. {
  1832. if(current > target + BED_HYSTERESIS)
  1833. {
  1834. soft_pwm_bed = 0;
  1835. timer02_set_pwm0(soft_pwm_bed << 1);
  1836. }
  1837. else if(current <= target - BED_HYSTERESIS)
  1838. {
  1839. soft_pwm_bed = MAX_BED_POWER>>1;
  1840. timer02_set_pwm0(soft_pwm_bed << 1);
  1841. }
  1842. }
  1843. else
  1844. {
  1845. soft_pwm_bed = 0;
  1846. timer02_set_pwm0(soft_pwm_bed << 1);
  1847. WRITE(HEATER_BED_PIN,LOW);
  1848. }
  1849. #endif //BED_LIMIT_SWITCHING
  1850. if(target==0)
  1851. {
  1852. soft_pwm_bed = 0;
  1853. timer02_set_pwm0(soft_pwm_bed << 1);
  1854. }
  1855. #endif //TEMP_SENSOR_BED
  1856. }
  1857. // ISR-safe temperatures
  1858. static volatile bool adc_values_ready = false;
  1859. float current_temperature_isr[EXTRUDERS];
  1860. int target_temperature_isr[EXTRUDERS];
  1861. float current_temperature_bed_isr;
  1862. int target_temperature_bed_isr;
  1863. #ifdef PINDA_THERMISTOR
  1864. float current_temperature_pinda_isr;
  1865. #endif
  1866. #ifdef AMBIENT_THERMISTOR
  1867. float current_temperature_ambient_isr;
  1868. #endif
  1869. // ISR callback from adc when sampling finished
  1870. void adc_callback()
  1871. {
  1872. current_temperature_raw[0] = adc_values[ADC_PIN_IDX(TEMP_0_PIN)]; //heater
  1873. current_temperature_bed_raw = adc_values[ADC_PIN_IDX(TEMP_BED_PIN)];
  1874. #ifdef PINDA_THERMISTOR
  1875. current_temperature_raw_pinda = adc_values[ADC_PIN_IDX(TEMP_PINDA_PIN)];
  1876. #endif //PINDA_THERMISTOR
  1877. #ifdef AMBIENT_THERMISTOR
  1878. current_temperature_raw_ambient = adc_values[ADC_PIN_IDX(TEMP_AMBIENT_PIN)]; // 5->6
  1879. #endif //AMBIENT_THERMISTOR
  1880. #ifdef VOLT_PWR_PIN
  1881. current_voltage_raw_pwr = adc_values[ADC_PIN_IDX(VOLT_PWR_PIN)];
  1882. #endif
  1883. #ifdef VOLT_BED_PIN
  1884. current_voltage_raw_bed = adc_values[ADC_PIN_IDX(VOLT_BED_PIN)]; // 6->9
  1885. #endif
  1886. #ifdef IR_SENSOR_ANALOG
  1887. current_voltage_raw_IR = adc_values[ADC_PIN_IDX(VOLT_IR_PIN)];
  1888. #endif //IR_SENSOR_ANALOG
  1889. adc_values_ready = true;
  1890. }
  1891. static void setCurrentTemperaturesFromIsr()
  1892. {
  1893. for(uint8_t e=0;e<EXTRUDERS;e++)
  1894. current_temperature[e] = current_temperature_isr[e];
  1895. current_temperature_bed = current_temperature_bed_isr;
  1896. #ifdef PINDA_THERMISTOR
  1897. current_temperature_pinda = current_temperature_pinda_isr;
  1898. #endif
  1899. #ifdef AMBIENT_THERMISTOR
  1900. current_temperature_ambient = current_temperature_ambient_isr;
  1901. #endif
  1902. }
  1903. static void setIsrTargetTemperatures()
  1904. {
  1905. for(uint8_t e=0;e<EXTRUDERS;e++)
  1906. target_temperature_isr[e] = target_temperature[e];
  1907. target_temperature_bed_isr = target_temperature_bed;
  1908. }
  1909. /* Synchronize temperatures:
  1910. - fetch updated values from temp_mgr_isr to current values
  1911. - update target temperatures for temp_mgr_isr regulation *if* no temperature error is set
  1912. This function is blocking: check temp_meas_ready before calling! */
  1913. static void updateTemperatures()
  1914. {
  1915. TempMgrGuard temp_mgr_guard;
  1916. setCurrentTemperaturesFromIsr();
  1917. if(!temp_error_state.v) {
  1918. // refuse to update target temperatures in any error condition!
  1919. setIsrTargetTemperatures();
  1920. }
  1921. temp_meas_ready = false;
  1922. }
  1923. /* Convert raw values into actual temperatures for temp_mgr. The raw values are created in the ADC
  1924. interrupt context, while this function runs from temp_mgr_isr which *is* preemptible as
  1925. analog2temp is relatively slow */
  1926. static void setIsrTemperaturesFromRawValues()
  1927. {
  1928. for(uint8_t e=0;e<EXTRUDERS;e++)
  1929. current_temperature_isr[e] = analog2temp(current_temperature_raw[e], e);
  1930. current_temperature_bed_isr = analog2tempBed(current_temperature_bed_raw);
  1931. #ifdef PINDA_THERMISTOR
  1932. current_temperature_pinda_isr = analog2tempBed(current_temperature_raw_pinda);
  1933. #endif
  1934. #ifdef AMBIENT_THERMISTOR
  1935. current_temperature_ambient_isr = analog2tempAmbient(current_temperature_raw_ambient); //thermistor for ambient is NTCG104LH104JT1 (2000)
  1936. #endif
  1937. temp_meas_ready = true;
  1938. }
  1939. static void temp_mgr_pid()
  1940. {
  1941. for(uint8_t e = 0; e < EXTRUDERS; e++)
  1942. pid_heater(e, current_temperature_isr[e], target_temperature_isr[e]);
  1943. pid_bed(current_temperature_bed_isr, target_temperature_bed_isr);
  1944. }
  1945. static void check_temp_runaway()
  1946. {
  1947. #ifdef TEMP_RUNAWAY_EXTRUDER_HYSTERESIS
  1948. for(uint8_t e = 0; e < EXTRUDERS; e++)
  1949. temp_runaway_check(e+1, target_temperature_isr[e], current_temperature_isr[e], soft_pwm[e], false);
  1950. #endif
  1951. #ifdef TEMP_RUNAWAY_BED_HYSTERESIS
  1952. temp_runaway_check(0, target_temperature_bed_isr, current_temperature_bed_isr, soft_pwm_bed, true);
  1953. #endif
  1954. }
  1955. static void check_temp_raw();
  1956. static void temp_mgr_isr()
  1957. {
  1958. // update *_isr temperatures from raw values for PID regulation
  1959. setIsrTemperaturesFromRawValues();
  1960. // clear the error assertion flag before checking again
  1961. temp_error_state.assert = false;
  1962. check_temp_raw(); // check min/max temp using raw values
  1963. check_temp_runaway(); // classic temperature hysteresis check
  1964. #ifdef TEMP_MODEL
  1965. temp_model::check(); // model-based heater check
  1966. #ifdef TEMP_MODEL_DEBUG
  1967. temp_model::log_isr();
  1968. #endif
  1969. #endif
  1970. // PID regulation
  1971. if (pid_tuning_finished)
  1972. temp_mgr_pid();
  1973. }
  1974. ISR(TIMER5_COMPA_vect)
  1975. {
  1976. // immediately schedule a new conversion
  1977. if(adc_values_ready != true) return;
  1978. adc_values_ready = false;
  1979. adc_start_cycle();
  1980. // run temperature management with interrupts enabled to reduce latency
  1981. DISABLE_TEMP_MGR_INTERRUPT();
  1982. sei();
  1983. temp_mgr_isr();
  1984. cli();
  1985. ENABLE_TEMP_MGR_INTERRUPT();
  1986. }
  1987. void disable_heater()
  1988. {
  1989. setAllTargetHotends(0);
  1990. setTargetBed(0);
  1991. CRITICAL_SECTION_START;
  1992. // propagate all values down the chain
  1993. setIsrTargetTemperatures();
  1994. temp_mgr_pid();
  1995. // we can't call soft_pwm_core directly to toggle the pins as it would require removing the inline
  1996. // attribute, so disable each pin individually
  1997. #if defined(HEATER_0_PIN) && HEATER_0_PIN > -1 && EXTRUDERS > 0
  1998. WRITE(HEATER_0_PIN,LOW);
  1999. #endif
  2000. #if defined(HEATER_1_PIN) && HEATER_1_PIN > -1 && EXTRUDERS > 1
  2001. WRITE(HEATER_1_PIN,LOW);
  2002. #endif
  2003. #if defined(HEATER_2_PIN) && HEATER_2_PIN > -1 && EXTRUDERS > 2
  2004. WRITE(HEATER_2_PIN,LOW);
  2005. #endif
  2006. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  2007. // TODO: this doesn't take immediate effect!
  2008. timer02_set_pwm0(0);
  2009. bedPWMDisabled = 0;
  2010. #endif
  2011. CRITICAL_SECTION_END;
  2012. }
  2013. static void check_min_temp_raw()
  2014. {
  2015. static bool bCheckingOnHeater = false; // state variable, which allows to short no-checking delay (is set, when temperature is (first time) over heaterMintemp)
  2016. static bool bCheckingOnBed = false; // state variable, which allows to short no-checking delay (is set, when temperature is (first time) over bedMintemp)
  2017. static ShortTimer oTimer4minTempHeater;
  2018. static ShortTimer oTimer4minTempBed;
  2019. #ifdef AMBIENT_THERMISTOR
  2020. #ifdef AMBIENT_MINTEMP
  2021. // we need to check ambient temperature
  2022. check_min_temp_ambient();
  2023. #endif
  2024. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  2025. if(current_temperature_raw_ambient>(OVERSAMPLENR*MINTEMP_MINAMBIENT_RAW)) // thermistor is NTC type
  2026. #else
  2027. if(current_temperature_raw_ambient=<(OVERSAMPLENR*MINTEMP_MINAMBIENT_RAW))
  2028. #endif
  2029. {
  2030. // ambient temperature is low
  2031. #endif //AMBIENT_THERMISTOR
  2032. // *** 'common' part of code for MK2.5 & MK3
  2033. // * nozzle checking
  2034. if(target_temperature_isr[active_extruder]>minttemp[active_extruder]) {
  2035. // ~ nozzle heating is on
  2036. bCheckingOnHeater=bCheckingOnHeater||(current_temperature_isr[active_extruder]>(minttemp[active_extruder]+TEMP_HYSTERESIS)); // for eventually delay cutting
  2037. if(oTimer4minTempHeater.expired(HEATER_MINTEMP_DELAY)||(!oTimer4minTempHeater.running())||bCheckingOnHeater) {
  2038. bCheckingOnHeater=true; // not necessary
  2039. check_min_temp_heater0(); // delay is elapsed or temperature is/was over minTemp => periodical checking is active
  2040. }
  2041. }
  2042. else {
  2043. // ~ nozzle heating is off
  2044. oTimer4minTempHeater.start();
  2045. bCheckingOnHeater=false;
  2046. }
  2047. // * bed checking
  2048. if(target_temperature_bed_isr>BED_MINTEMP) {
  2049. // ~ bed heating is on
  2050. bCheckingOnBed=bCheckingOnBed||(current_temperature_bed_isr>(BED_MINTEMP+TEMP_HYSTERESIS)); // for eventually delay cutting
  2051. if(oTimer4minTempBed.expired(BED_MINTEMP_DELAY)||(!oTimer4minTempBed.running())||bCheckingOnBed) {
  2052. bCheckingOnBed=true; // not necessary
  2053. check_min_temp_bed(); // delay is elapsed or temperature is/was over minTemp => periodical checking is active
  2054. }
  2055. }
  2056. else {
  2057. // ~ bed heating is off
  2058. oTimer4minTempBed.start();
  2059. bCheckingOnBed=false;
  2060. }
  2061. // *** end of 'common' part
  2062. #ifdef AMBIENT_THERMISTOR
  2063. }
  2064. else {
  2065. // ambient temperature is standard
  2066. check_min_temp_heater0();
  2067. check_min_temp_bed();
  2068. }
  2069. #endif //AMBIENT_THERMISTOR
  2070. }
  2071. static void check_temp_raw()
  2072. {
  2073. // order is relevant: check_min_temp_raw requires max to be reliable due to
  2074. // ambient temperature being used for low handling temperatures
  2075. check_max_temp_raw();
  2076. check_min_temp_raw();
  2077. }
  2078. #ifdef TEMP_MODEL
  2079. namespace temp_model {
  2080. void model_data::reset(uint8_t heater_pwm, uint8_t fan_pwm, float heater_temp, float ambient_temp)
  2081. {
  2082. // pre-compute invariant values
  2083. C_i = (TEMP_MGR_INTV / C);
  2084. warn_s = warn * TEMP_MGR_INTV;
  2085. err_s = err * TEMP_MGR_INTV;
  2086. // initial values
  2087. memset(dT_lag_buf, 0, sizeof(dT_lag_buf));
  2088. dT_lag_idx = 0;
  2089. dT_err_prev = 0;
  2090. T_prev = heater_temp;
  2091. // perform one step to initialize the first delta
  2092. step(heater_pwm, fan_pwm, heater_temp, ambient_temp);
  2093. // clear the initialization flag
  2094. flag_bits.uninitialized = false;
  2095. }
  2096. void model_data::step(uint8_t heater_pwm, uint8_t fan_pwm, float heater_temp, float ambient_temp)
  2097. {
  2098. constexpr float soft_pwm_inv = 1. / ((1 << 7) - 1);
  2099. // input values
  2100. const float heater_scale = soft_pwm_inv * heater_pwm;
  2101. const float cur_heater_temp = heater_temp;
  2102. const float cur_ambient_temp = ambient_temp + Ta_corr;
  2103. const float cur_R = R[fan_pwm]; // resistance at current fan power (K/W)
  2104. float dP = P * heater_scale; // current power [W]
  2105. float dPl = (cur_heater_temp - cur_ambient_temp) / cur_R; // [W] leakage power
  2106. float dT = (dP - dPl) * C_i; // expected temperature difference (K)
  2107. // filter and lag dT
  2108. uint8_t dT_next_idx = (dT_lag_idx == (TEMP_MODEL_LAG_SIZE - 1) ? 0: dT_lag_idx + 1);
  2109. float dT_lag = dT_lag_buf[dT_next_idx];
  2110. float dT_lag_prev = dT_lag_buf[dT_lag_idx];
  2111. float dT_f = (dT_lag_prev * (1.f - TEMP_MODEL_fS)) + (dT * TEMP_MODEL_fS);
  2112. dT_lag_buf[dT_next_idx] = dT_f;
  2113. dT_lag_idx = dT_next_idx;
  2114. // calculate and filter dT_err
  2115. float dT_err = (cur_heater_temp - T_prev) - dT_lag;
  2116. float dT_err_f = (dT_err_prev * (1.f - TEMP_MODEL_fE)) + (dT_err * TEMP_MODEL_fE);
  2117. T_prev = cur_heater_temp;
  2118. dT_err_prev = dT_err_f;
  2119. // check and trigger errors
  2120. flag_bits.error = (fabsf(dT_err_f) > err_s);
  2121. flag_bits.warning = (fabsf(dT_err_f) > warn_s);
  2122. }
  2123. // verify calibration status and trigger a model reset if valid
  2124. void setup()
  2125. {
  2126. if(!calibrated()) enabled = false;
  2127. data.flag_bits.uninitialized = true;
  2128. }
  2129. bool calibrated()
  2130. {
  2131. if(!(data.P >= 0)) return false;
  2132. if(!(data.C >= 0)) return false;
  2133. if(!(data.Ta_corr != NAN)) return false;
  2134. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i) {
  2135. if(!(temp_model::data.R[i] >= 0))
  2136. return false;
  2137. }
  2138. if(!(data.warn != NAN)) return false;
  2139. if(!(data.err != NAN)) return false;
  2140. return true;
  2141. }
  2142. void check()
  2143. {
  2144. if(!enabled) return;
  2145. uint8_t heater_pwm = soft_pwm[0];
  2146. uint8_t fan_pwm = soft_pwm_fan;
  2147. float heater_temp = current_temperature_isr[0];
  2148. float ambient_temp = current_temperature_ambient_isr;
  2149. // check if a reset is required to seed the model: this needs to be done with valid
  2150. // ADC values, so we can't do that directly in init()
  2151. if(data.flag_bits.uninitialized)
  2152. data.reset(heater_pwm, fan_pwm, heater_temp, ambient_temp);
  2153. // step the model
  2154. data.step(heater_pwm, fan_pwm, heater_temp, ambient_temp);
  2155. // handle errors
  2156. if(data.flag_bits.error)
  2157. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::model);
  2158. // handle warning conditions as lower-priority but with greater feedback
  2159. warning_state.assert = data.flag_bits.warning;
  2160. if(warning_state.assert) {
  2161. warning_state.warning = true;
  2162. warning_state.dT_err = temp_model::data.dT_err_prev;
  2163. }
  2164. }
  2165. void handle_warning()
  2166. {
  2167. // update values
  2168. float warn = data.warn;
  2169. float dT_err;
  2170. {
  2171. TempMgrGuard temp_mgr_guard;
  2172. dT_err = warning_state.dT_err;
  2173. }
  2174. dT_err /= TEMP_MGR_INTV; // per-sample => K/s
  2175. // TODO: alert the user on the lcd
  2176. printf_P(PSTR("TM: error |%f|>%f\n"), (double)dT_err, (double)warn);
  2177. static bool beeper = false;
  2178. if(warning_state.assert) {
  2179. if(warn_beep) {
  2180. // beep periodically
  2181. beeper = !beeper;
  2182. WRITE(BEEPER, beeper);
  2183. }
  2184. } else {
  2185. // warning cleared, reset state
  2186. warning_state.warning = false;
  2187. if(warn_beep) {
  2188. beeper = false;
  2189. WRITE(BEEPER, LOW);
  2190. }
  2191. }
  2192. }
  2193. #ifdef TEMP_MODEL_DEBUG
  2194. void log_usr()
  2195. {
  2196. if(!log_buf.enabled) return;
  2197. uint8_t counter = log_buf.entry.counter;
  2198. if (counter == log_buf.serial) return;
  2199. int8_t delta_ms;
  2200. uint8_t cur_pwm;
  2201. // avoid strict-aliasing warnings
  2202. union { float cur_temp; uint32_t cur_temp_b; };
  2203. union { float cur_amb; uint32_t cur_amb_b; };
  2204. {
  2205. TempMgrGuard temp_mgr_guard;
  2206. delta_ms = log_buf.entry.delta_ms;
  2207. counter = log_buf.entry.counter;
  2208. cur_pwm = log_buf.entry.cur_pwm;
  2209. cur_temp = log_buf.entry.cur_temp;
  2210. cur_amb = log_buf.entry.cur_amb;
  2211. }
  2212. uint8_t d = counter - log_buf.serial;
  2213. log_buf.serial = counter;
  2214. printf_P(PSTR("TML %d %d %x %lx %lx\n"), (unsigned)d - 1, (int)delta_ms + 1,
  2215. (int)cur_pwm, (unsigned long)cur_temp_b, (unsigned long)cur_amb_b);
  2216. }
  2217. void log_isr()
  2218. {
  2219. if(!log_buf.enabled) return;
  2220. uint32_t stamp = _millis();
  2221. uint8_t delta_ms = stamp - log_buf.entry.stamp - (TEMP_MGR_INTV * 1000);
  2222. log_buf.entry.stamp = stamp;
  2223. ++log_buf.entry.counter;
  2224. log_buf.entry.delta_ms = delta_ms;
  2225. log_buf.entry.cur_pwm = soft_pwm[0];
  2226. log_buf.entry.cur_temp = current_temperature_isr[0];
  2227. log_buf.entry.cur_amb = current_temperature_ambient_isr;
  2228. }
  2229. #endif
  2230. } // namespace temp_model
  2231. void temp_model_set_enabled(bool enabled)
  2232. {
  2233. // set the enabled flag
  2234. {
  2235. TempMgrGuard temp_mgr_guard;
  2236. temp_model::enabled = enabled;
  2237. temp_model::setup();
  2238. }
  2239. // verify that the model has been enabled
  2240. if(enabled && !temp_model::enabled)
  2241. SERIAL_ECHOLNPGM("TM: invalid parameters, cannot enable");
  2242. }
  2243. void temp_model_set_warn_beep(bool enabled)
  2244. {
  2245. temp_model::warn_beep = enabled;
  2246. }
  2247. void temp_model_set_params(float C, float P, float Ta_corr, float warn, float err)
  2248. {
  2249. TempMgrGuard temp_mgr_guard;
  2250. if(!isnan(C) && C > 0) temp_model::data.C = C;
  2251. if(!isnan(P) && P > 0) temp_model::data.P = P;
  2252. if(!isnan(Ta_corr)) temp_model::data.Ta_corr = Ta_corr;
  2253. if(!isnan(err) && err > 0) temp_model::data.err = err;
  2254. if(!isnan(warn) && warn > 0) temp_model::data.warn = warn;
  2255. // ensure warn <= err
  2256. if (temp_model::data.warn > temp_model::data.err)
  2257. temp_model::data.warn = temp_model::data.err;
  2258. temp_model::setup();
  2259. }
  2260. void temp_model_set_resistance(uint8_t index, float R)
  2261. {
  2262. if(index >= TEMP_MODEL_R_SIZE || R <= 0)
  2263. return;
  2264. TempMgrGuard temp_mgr_guard;
  2265. temp_model::data.R[index] = R;
  2266. temp_model::setup();
  2267. }
  2268. void temp_model_report_settings()
  2269. {
  2270. SERIAL_ECHO_START;
  2271. SERIAL_ECHOLNPGM("Temperature Model settings:");
  2272. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2273. printf_P(PSTR("%S M310 I%u R%.2f\n"), echomagic, (unsigned)i, (double)temp_model::data.R[i]);
  2274. printf_P(PSTR("%S M310 P%.2f C%.2f S%u B%u E%.2f W%.2f T%.2f\n"),
  2275. echomagic, (double)temp_model::data.P, (double)temp_model::data.C,
  2276. (unsigned)temp_model::enabled, (unsigned)temp_model::warn_beep,
  2277. (double)temp_model::data.err, (double)temp_model::data.warn,
  2278. (double)temp_model::data.Ta_corr);
  2279. }
  2280. void temp_model_reset_settings()
  2281. {
  2282. TempMgrGuard temp_mgr_guard;
  2283. temp_model::data.P = TEMP_MODEL_P;
  2284. temp_model::data.C = NAN;
  2285. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2286. temp_model::data.R[i] = NAN;
  2287. temp_model::data.Ta_corr = TEMP_MODEL_Ta_corr;
  2288. temp_model::data.warn = TEMP_MODEL_W;
  2289. temp_model::data.err = TEMP_MODEL_E;
  2290. temp_model::warn_beep = true;
  2291. temp_model::enabled = false;
  2292. }
  2293. void temp_model_load_settings()
  2294. {
  2295. static_assert(TEMP_MODEL_R_SIZE == 16); // ensure we don't desync with the eeprom table
  2296. TempMgrGuard temp_mgr_guard;
  2297. temp_model::enabled = eeprom_read_byte((uint8_t*)EEPROM_TEMP_MODEL_ENABLE);
  2298. temp_model::data.P = eeprom_read_float((float*)EEPROM_TEMP_MODEL_P);
  2299. temp_model::data.C = eeprom_read_float((float*)EEPROM_TEMP_MODEL_C);
  2300. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2301. temp_model::data.R[i] = eeprom_read_float((float*)EEPROM_TEMP_MODEL_R + i);
  2302. temp_model::data.Ta_corr = eeprom_read_float((float*)EEPROM_TEMP_MODEL_Ta_corr);
  2303. temp_model::data.warn = eeprom_read_float((float*)EEPROM_TEMP_MODEL_W);
  2304. temp_model::data.err = eeprom_read_float((float*)EEPROM_TEMP_MODEL_E);
  2305. if(!temp_model::calibrated()) {
  2306. SERIAL_ECHOLNPGM("TM: stored calibration invalid, resetting");
  2307. temp_model_reset_settings();
  2308. }
  2309. temp_model::setup();
  2310. }
  2311. void temp_model_save_settings()
  2312. {
  2313. eeprom_update_byte((uint8_t*)EEPROM_TEMP_MODEL_ENABLE, temp_model::enabled);
  2314. eeprom_update_float((float*)EEPROM_TEMP_MODEL_P, temp_model::data.P);
  2315. eeprom_update_float((float*)EEPROM_TEMP_MODEL_C, temp_model::data.C);
  2316. for(uint8_t i = 0; i != TEMP_MODEL_R_SIZE; ++i)
  2317. eeprom_update_float((float*)EEPROM_TEMP_MODEL_R + i, temp_model::data.R[i]);
  2318. eeprom_update_float((float*)EEPROM_TEMP_MODEL_Ta_corr, temp_model::data.Ta_corr);
  2319. eeprom_update_float((float*)EEPROM_TEMP_MODEL_W, temp_model::data.warn);
  2320. eeprom_update_float((float*)EEPROM_TEMP_MODEL_E, temp_model::data.err);
  2321. }
  2322. namespace temp_model_cal {
  2323. void waiting_handler()
  2324. {
  2325. manage_heater();
  2326. host_keepalive();
  2327. host_autoreport();
  2328. lcd_update(0);
  2329. }
  2330. void wait(unsigned ms)
  2331. {
  2332. unsigned long mark = _millis() + ms;
  2333. while(_millis() < mark) {
  2334. if(temp_error_state.v) break;
  2335. waiting_handler();
  2336. }
  2337. }
  2338. void wait_temp()
  2339. {
  2340. while(current_temperature[0] < (target_temperature[0] - TEMP_HYSTERESIS)) {
  2341. if(temp_error_state.v) break;
  2342. waiting_handler();
  2343. }
  2344. }
  2345. void cooldown(float temp)
  2346. {
  2347. float old_speed = fanSpeedSoftPwm;
  2348. fanSpeedSoftPwm = 255;
  2349. while(current_temperature[0] >= temp) {
  2350. if(temp_error_state.v) break;
  2351. float ambient = current_temperature_ambient + temp_model::data.Ta_corr;
  2352. if(current_temperature[0] < (ambient + TEMP_HYSTERESIS)) {
  2353. // do not get stuck waiting very close to ambient temperature
  2354. break;
  2355. }
  2356. waiting_handler();
  2357. }
  2358. fanSpeedSoftPwm = old_speed;
  2359. }
  2360. uint16_t record(uint16_t samples = REC_BUFFER_SIZE) {
  2361. TempMgrGuard temp_mgr_guard;
  2362. uint16_t pos = 0;
  2363. while(pos < samples) {
  2364. if(!TEMP_MGR_INT_FLAG_STATE()) {
  2365. // temperatures not ready yet, just manage heaters while waiting to reduce jitter
  2366. manage_heater();
  2367. continue;
  2368. }
  2369. TEMP_MGR_INT_FLAG_CLEAR();
  2370. // manually repeat what the regular isr would do
  2371. if(adc_values_ready != true) continue;
  2372. adc_values_ready = false;
  2373. adc_start_cycle();
  2374. temp_mgr_isr();
  2375. // stop recording for an hard error condition
  2376. if(temp_error_state.v)
  2377. return 0;
  2378. // record a new entry
  2379. rec_entry& entry = rec_buffer[pos];
  2380. entry.temp = current_temperature_isr[0];
  2381. entry.pwm = soft_pwm[0];
  2382. ++pos;
  2383. // it's now safer to give regular serial/lcd updates a shot
  2384. waiting_handler();
  2385. }
  2386. return pos;
  2387. }
  2388. float cost_fn(uint16_t samples, float* const var, float v, float ambient)
  2389. {
  2390. *var = v;
  2391. uint8_t fan_pwm = soft_pwm_fan;
  2392. temp_model::data.reset(rec_buffer[0].pwm, fan_pwm, rec_buffer[0].temp, ambient);
  2393. float err = 0;
  2394. for(uint16_t i = 1; i < samples; ++i) {
  2395. temp_model::data.step(rec_buffer[i].pwm, fan_pwm, rec_buffer[i].temp, ambient);
  2396. err += fabsf(temp_model::data.dT_err_prev);
  2397. }
  2398. return (err / (samples - 1));
  2399. }
  2400. constexpr float GOLDEN_RATIO = 0.6180339887498949;
  2401. void update_section(float points[2], const float bounds[2])
  2402. {
  2403. float d = GOLDEN_RATIO * (bounds[1] - bounds[0]);
  2404. points[0] = bounds[0] + d;
  2405. points[1] = bounds[1] - d;
  2406. }
  2407. float estimate(uint16_t samples, float* const var, float min, float max, float thr, uint16_t max_itr, float ambient)
  2408. {
  2409. float e = NAN;
  2410. float points[2];
  2411. float bounds[2] = {min, max};
  2412. update_section(points, bounds);
  2413. for(uint8_t it = 0; it != max_itr; ++it) {
  2414. float c1 = cost_fn(samples, var, points[0], ambient);
  2415. float c2 = cost_fn(samples, var, points[1], ambient);
  2416. bool dir = (c2 < c1);
  2417. bounds[dir] = points[!dir];
  2418. update_section(points, bounds);
  2419. float x = points[!dir];
  2420. e = (1-GOLDEN_RATIO) * fabsf((bounds[0]-bounds[1]) / x);
  2421. printf_P(PSTR("TM iter:%u v:%.2f e:%.3f\n"), it, x, e);
  2422. if(e < thr) return e;
  2423. }
  2424. SERIAL_ECHOLNPGM("TM estimation did not converge");
  2425. return NAN;
  2426. }
  2427. bool autotune(int16_t cal_temp)
  2428. {
  2429. uint16_t samples;
  2430. float e;
  2431. // bootstrap C/R values without fan
  2432. fanSpeedSoftPwm = 0;
  2433. for(uint8_t i = 0; i != 2; ++i) {
  2434. const char* PROGMEM verb = (i == 0? PSTR("initial"): PSTR("refining"));
  2435. target_temperature[0] = 0;
  2436. if(current_temperature[0] >= TEMP_MODEL_CAL_Tl) {
  2437. printf_P(PSTR("TM: cooling down to %dC\n"), TEMP_MODEL_CAL_Tl);
  2438. cooldown(TEMP_MODEL_CAL_Tl);
  2439. wait(10000);
  2440. }
  2441. // we need a valid R value for the initial C guess
  2442. if(isnan(temp_model::data.R[0]))
  2443. temp_model::data.R[0] = TEMP_MODEL_Rh;
  2444. printf_P(PSTR("TM: %S C estimation\n"), verb);
  2445. target_temperature[0] = cal_temp;
  2446. samples = record();
  2447. if(temp_error_state.v || !samples)
  2448. return true;
  2449. e = estimate(samples, &temp_model::data.C,
  2450. TEMP_MODEL_Cl, TEMP_MODEL_Ch, TEMP_MODEL_C_thr, TEMP_MODEL_C_itr,
  2451. current_temperature_ambient);
  2452. if(isnan(e))
  2453. return true;
  2454. wait_temp();
  2455. if(i) break; // we don't need to refine R
  2456. wait(30000); // settle PID regulation
  2457. printf_P(PSTR("TM: %S R estimation @ %dC\n"), verb, cal_temp);
  2458. samples = record();
  2459. if(temp_error_state.v || !samples)
  2460. return true;
  2461. e = estimate(samples, &temp_model::data.R[0],
  2462. TEMP_MODEL_Rl, TEMP_MODEL_Rh, TEMP_MODEL_R_thr, TEMP_MODEL_R_itr,
  2463. current_temperature_ambient);
  2464. if(isnan(e))
  2465. return true;
  2466. }
  2467. // Estimate fan losses at regular intervals, starting from full speed to avoid low-speed
  2468. // kickstart issues, although this requires us to wait more for the PID stabilization.
  2469. // Normally exhibits logarithmic behavior with the stock fan+shroud, so the shorter interval
  2470. // at lower speeds is helpful to increase the resolution of the interpolation.
  2471. fanSpeedSoftPwm = 255;
  2472. wait(30000);
  2473. for(int8_t i = TEMP_MODEL_R_SIZE; i > 0; i -= TEMP_MODEL_CAL_R_STEP) {
  2474. fanSpeedSoftPwm = 256 / TEMP_MODEL_R_SIZE * i - 1;
  2475. wait(10000);
  2476. printf_P(PSTR("TM: R[%u] estimation\n"), (unsigned)soft_pwm_fan);
  2477. samples = record();
  2478. if(temp_error_state.v || !samples)
  2479. return true;
  2480. e = estimate(samples, &temp_model::data.R[soft_pwm_fan],
  2481. TEMP_MODEL_Rl, temp_model::data.R[0], TEMP_MODEL_R_thr, TEMP_MODEL_R_itr,
  2482. current_temperature_ambient);
  2483. if(isnan(e))
  2484. return true;
  2485. }
  2486. // interpolate remaining steps to speed-up calibration
  2487. int8_t next = TEMP_MODEL_R_SIZE - 1;
  2488. for(uint8_t i = TEMP_MODEL_R_SIZE - 2; i != 0; --i) {
  2489. if(!((TEMP_MODEL_R_SIZE - i - 1) % TEMP_MODEL_CAL_R_STEP)) {
  2490. next = i;
  2491. continue;
  2492. }
  2493. int8_t prev = next - TEMP_MODEL_CAL_R_STEP;
  2494. if(prev < 0) prev = 0;
  2495. float f = (float)(i - prev) / TEMP_MODEL_CAL_R_STEP;
  2496. float d = (temp_model::data.R[next] - temp_model::data.R[prev]);
  2497. temp_model::data.R[i] = temp_model::data.R[prev] + d * f;
  2498. }
  2499. return false;
  2500. }
  2501. } // namespace temp_model_cal
  2502. void temp_model_autotune(int16_t temp)
  2503. {
  2504. if(moves_planned() || printer_active()) {
  2505. SERIAL_ECHOLNPGM("TM: printer needs to be idle for calibration");
  2506. return;
  2507. }
  2508. KEEPALIVE_STATE(IN_PROCESS);
  2509. // disable the model checking during self-calibration
  2510. bool was_enabled = temp_model::enabled;
  2511. temp_model_set_enabled(false);
  2512. SERIAL_ECHOLNPGM("TM: autotune start");
  2513. bool err = temp_model_cal::autotune(temp > 0 ? temp : TEMP_MODEL_CAL_Th);
  2514. // always reset temperature
  2515. target_temperature[0] = 0;
  2516. if(err) {
  2517. SERIAL_ECHOLNPGM("TM: autotune failed");
  2518. if(temp_error_state.v)
  2519. fanSpeedSoftPwm = 255;
  2520. } else {
  2521. fanSpeedSoftPwm = 0;
  2522. temp_model_set_enabled(was_enabled);
  2523. temp_model_report_settings();
  2524. }
  2525. }
  2526. #ifdef TEMP_MODEL_DEBUG
  2527. void temp_model_log_enable(bool enable)
  2528. {
  2529. if(enable) {
  2530. TempMgrGuard temp_mgr_guard;
  2531. temp_model::log_buf.entry.stamp = _millis();
  2532. }
  2533. temp_model::log_buf.enabled = enable;
  2534. }
  2535. #endif
  2536. #endif