temperature.cpp 83 KB

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