temperature.cpp 84 KB

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