temperature.cpp 84 KB

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