temperature.cpp 86 KB

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