temperature.cpp 85 KB

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