temperature.cpp 87 KB

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