temperature.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881
  1. /*
  2. temperature.c - temperature control
  3. Part of Marlin
  4. Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /*
  17. This firmware is a mashup between Sprinter and grbl.
  18. (https://github.com/kliment/Sprinter)
  19. (https://github.com/simen/grbl/tree)
  20. It has preliminary support for Matthew Roberts advance algorithm
  21. http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  22. */
  23. #include "temperature.h"
  24. #include "stepper.h"
  25. #include "ultralcd.h"
  26. #include "menu.h"
  27. #include "sound.h"
  28. #include "fancheck.h"
  29. #include "messages.h"
  30. #include "SdFatUtil.h"
  31. #include <avr/wdt.h>
  32. #include <util/atomic.h>
  33. #include "adc.h"
  34. #include "ConfigurationStore.h"
  35. #include "Timer.h"
  36. #include "Configuration_prusa.h"
  37. #if (ADC_OVRSAMPL != OVERSAMPLENR)
  38. #error "ADC_OVRSAMPL oversampling must match OVERSAMPLENR"
  39. #endif
  40. // temperature manager timer configuration
  41. #define TEMP_MGR_INTV 0.27 // seconds, ~3.7Hz
  42. #define TIMER5_PRESCALE 256
  43. #define TIMER5_OCRA_OVF (uint16_t)(TEMP_MGR_INTV / ((long double)TIMER5_PRESCALE / F_CPU))
  44. #define TEMP_MGR_INT_FLAG_STATE() (TIFR5 & (1<<OCF5A))
  45. #define TEMP_MGR_INT_FLAG_CLEAR() TIFR5 |= (1<<OCF5A)
  46. #define TEMP_MGR_INTERRUPT_STATE() (TIMSK5 & (1<<OCIE5A))
  47. #define ENABLE_TEMP_MGR_INTERRUPT() TIMSK5 |= (1<<OCIE5A)
  48. #define DISABLE_TEMP_MGR_INTERRUPT() TIMSK5 &= ~(1<<OCIE5A)
  49. #ifdef TEMP_MODEL
  50. // temperature model interface
  51. #include "temp_model.h"
  52. #endif
  53. //===========================================================================
  54. //=============================public variables============================
  55. //===========================================================================
  56. int target_temperature[EXTRUDERS] = { 0 };
  57. int target_temperature_bed = 0;
  58. int current_temperature_raw[EXTRUDERS] = { 0 };
  59. float current_temperature[EXTRUDERS] = { 0.0 };
  60. #ifdef PINDA_THERMISTOR
  61. uint16_t current_temperature_raw_pinda = 0;
  62. float current_temperature_pinda = 0.0;
  63. #endif //PINDA_THERMISTOR
  64. #ifdef AMBIENT_THERMISTOR
  65. int current_temperature_raw_ambient = 0;
  66. float current_temperature_ambient = 0.0;
  67. #endif //AMBIENT_THERMISTOR
  68. #ifdef VOLT_PWR_PIN
  69. int current_voltage_raw_pwr = 0;
  70. #endif
  71. #ifdef VOLT_BED_PIN
  72. int current_voltage_raw_bed = 0;
  73. #endif
  74. #ifdef IR_SENSOR_ANALOG
  75. uint16_t current_voltage_raw_IR = 0;
  76. #endif //IR_SENSOR_ANALOG
  77. int current_temperature_bed_raw = 0;
  78. float current_temperature_bed = 0.0;
  79. #ifdef PIDTEMP
  80. float _Kp, _Ki, _Kd;
  81. int pid_cycle, pid_number_of_cycles;
  82. static bool pid_tuning_finished = true;
  83. bool pidTuningRunning() {
  84. return !pid_tuning_finished;
  85. }
  86. void preparePidTuning() {
  87. // ensure heaters are disabled before we switch off PID management!
  88. disable_heater();
  89. pid_tuning_finished = false;
  90. }
  91. #endif //PIDTEMP
  92. unsigned char soft_pwm_bed;
  93. #ifdef BABYSTEPPING
  94. volatile int babystepsTodo[3]={0,0,0};
  95. #endif
  96. //===========================================================================
  97. //=============================private variables============================
  98. //===========================================================================
  99. static volatile bool temp_meas_ready = false;
  100. #ifdef PIDTEMP
  101. //static cannot be external:
  102. static float iState_sum[EXTRUDERS] = { 0 };
  103. static float dState_last[EXTRUDERS] = { 0 };
  104. static float pTerm[EXTRUDERS];
  105. static float iTerm[EXTRUDERS];
  106. static float dTerm[EXTRUDERS];
  107. static float pid_error[EXTRUDERS];
  108. static float iState_sum_min[EXTRUDERS];
  109. static float iState_sum_max[EXTRUDERS];
  110. static bool pid_reset[EXTRUDERS];
  111. #endif //PIDTEMP
  112. #ifdef PIDTEMPBED
  113. //static cannot be external:
  114. static float temp_iState_bed = { 0 };
  115. static float temp_dState_bed = { 0 };
  116. static float pTerm_bed;
  117. static float iTerm_bed;
  118. static float dTerm_bed;
  119. static float pid_error_bed;
  120. static float temp_iState_min_bed;
  121. static float temp_iState_max_bed;
  122. #else //PIDTEMPBED
  123. static unsigned long previous_millis_bed_heater;
  124. #endif //PIDTEMPBED
  125. static unsigned char soft_pwm[EXTRUDERS];
  126. #ifdef FAN_SOFT_PWM
  127. unsigned char fanSpeedSoftPwm;
  128. static unsigned char soft_pwm_fan;
  129. #endif
  130. uint8_t fanSpeedBckp = 255;
  131. #if EXTRUDERS > 3
  132. # error Unsupported number of extruders
  133. #elif EXTRUDERS > 2
  134. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1, v2, v3 }
  135. #elif EXTRUDERS > 1
  136. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1, v2 }
  137. #else
  138. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1 }
  139. #endif
  140. // Init min and max temp with extreme values to prevent false errors during startup
  141. static int minttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP );
  142. static int maxttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP );
  143. static int minttemp[EXTRUDERS] = ARRAY_BY_EXTRUDERS( 0, 0, 0 );
  144. static int maxttemp[EXTRUDERS] = ARRAY_BY_EXTRUDERS( 16383, 16383, 16383 );
  145. #ifdef BED_MINTEMP
  146. static int bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
  147. #endif
  148. #ifdef BED_MAXTEMP
  149. static int bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
  150. #endif
  151. #ifdef AMBIENT_MINTEMP
  152. static int ambient_minttemp_raw = AMBIENT_RAW_LO_TEMP;
  153. #endif
  154. #ifdef AMBIENT_MAXTEMP
  155. static int ambient_maxttemp_raw = AMBIENT_RAW_HI_TEMP;
  156. #endif
  157. static void *heater_ttbl_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS( (void *)HEATER_0_TEMPTABLE, (void *)HEATER_1_TEMPTABLE, (void *)HEATER_2_TEMPTABLE );
  158. static uint8_t heater_ttbllen_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN );
  159. static float analog2temp(int raw, uint8_t e);
  160. static float analog2tempBed(int raw);
  161. #ifdef AMBIENT_MAXTEMP
  162. static float analog2tempAmbient(int raw);
  163. #endif
  164. static void updateTemperatures();
  165. enum TempRunawayStates : uint8_t
  166. {
  167. TempRunaway_INACTIVE = 0,
  168. TempRunaway_PREHEAT = 1,
  169. TempRunaway_ACTIVE = 2,
  170. };
  171. #ifndef SOFT_PWM_SCALE
  172. #define SOFT_PWM_SCALE 0
  173. #endif
  174. //===========================================================================
  175. //============================= functions ============================
  176. //===========================================================================
  177. #if (defined (TEMP_RUNAWAY_BED_HYSTERESIS) && TEMP_RUNAWAY_BED_TIMEOUT > 0) || (defined (TEMP_RUNAWAY_EXTRUDER_HYSTERESIS) && TEMP_RUNAWAY_EXTRUDER_TIMEOUT > 0)
  178. static uint8_t temp_runaway_status[1 + EXTRUDERS];
  179. static float temp_runaway_target[1 + EXTRUDERS];
  180. static uint32_t temp_runaway_timer[1 + EXTRUDERS];
  181. static uint16_t temp_runaway_error_counter[1 + EXTRUDERS];
  182. static void temp_runaway_check(uint8_t _heater_id, float _target_temperature, float _current_temperature, float _output, bool _isbed);
  183. static void temp_runaway_stop(bool isPreheat, bool isBed);
  184. #endif
  185. // return "false", if all extruder-heaters are 'off' (ie. "true", if any heater is 'on')
  186. bool checkAllHotends(void)
  187. {
  188. bool result=false;
  189. for(int i=0;i<EXTRUDERS;i++) result=(result||(target_temperature[i]!=0));
  190. return(result);
  191. }
  192. // WARNING: the following function has been marked noinline to avoid a GCC 4.9.2 LTO
  193. // codegen bug causing a stack overwrite issue in process_commands()
  194. void __attribute__((noinline)) PID_autotune(float temp, int extruder, int ncycles)
  195. {
  196. preparePidTuning();
  197. pid_number_of_cycles = ncycles;
  198. float input = 0.0;
  199. pid_cycle=0;
  200. bool heating = true;
  201. unsigned long temp_millis = _millis();
  202. unsigned long t1=temp_millis;
  203. unsigned long t2=temp_millis;
  204. long t_high = 0;
  205. long t_low = 0;
  206. long bias, d;
  207. float Ku, Tu;
  208. float max = 0, min = 10000;
  209. uint8_t safety_check_cycles = 0;
  210. const uint8_t safety_check_cycles_count = (extruder < 0) ? 45 : 10; //10 cycles / 20s delay for extruder and 45 cycles / 90s for heatbed
  211. float temp_ambient;
  212. #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1)
  213. unsigned long extruder_autofan_last_check = _millis();
  214. #endif
  215. if ((extruder >= EXTRUDERS)
  216. #if (TEMP_BED_PIN <= -1)
  217. ||(extruder < 0)
  218. #endif
  219. ){
  220. SERIAL_ECHOLNPGM("PID Autotune failed. Bad extruder number.");
  221. pid_tuning_finished = true;
  222. pid_cycle = 0;
  223. return;
  224. }
  225. SERIAL_ECHOLNPGM("PID Autotune start");
  226. if (extruder<0)
  227. {
  228. soft_pwm_bed = (MAX_BED_POWER)/2;
  229. timer02_set_pwm0(soft_pwm_bed << 1);
  230. bias = d = (MAX_BED_POWER)/2;
  231. target_temperature_bed = (int)temp; // to display the requested target bed temperature properly on the main screen
  232. }
  233. else
  234. {
  235. soft_pwm[extruder] = (PID_MAX)/2;
  236. bias = d = (PID_MAX)/2;
  237. target_temperature[extruder] = (int)temp; // to display the requested target extruder temperature properly on the main screen
  238. }
  239. for(;;) {
  240. #ifdef WATCHDOG
  241. wdt_reset();
  242. #endif //WATCHDOG
  243. if(temp_meas_ready == true) { // temp sample ready
  244. updateTemperatures();
  245. input = (extruder<0)?current_temperature_bed:current_temperature[extruder];
  246. max=max(max,input);
  247. min=min(min,input);
  248. #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1)
  249. if(_millis() - extruder_autofan_last_check > 2500) {
  250. checkExtruderAutoFans();
  251. extruder_autofan_last_check = _millis();
  252. }
  253. #endif
  254. if(heating == true && input > temp) {
  255. if(_millis() - t2 > 5000) {
  256. heating=false;
  257. if (extruder<0)
  258. {
  259. soft_pwm_bed = (bias - d) >> 1;
  260. timer02_set_pwm0(soft_pwm_bed << 1);
  261. }
  262. else
  263. soft_pwm[extruder] = (bias - d) >> 1;
  264. t1=_millis();
  265. t_high=t1 - t2;
  266. max=temp;
  267. }
  268. }
  269. if(heating == false && input < temp) {
  270. if(_millis() - t1 > 5000) {
  271. heating=true;
  272. t2=_millis();
  273. t_low=t2 - t1;
  274. if(pid_cycle > 0) {
  275. bias += (d*(t_high - t_low))/(t_low + t_high);
  276. bias = constrain(bias, 20 ,(extruder<0?(MAX_BED_POWER):(PID_MAX))-20);
  277. if(bias > (extruder<0?(MAX_BED_POWER):(PID_MAX))/2) d = (extruder<0?(MAX_BED_POWER):(PID_MAX)) - 1 - bias;
  278. else d = bias;
  279. SERIAL_PROTOCOLPGM(" bias: "); SERIAL_PROTOCOL(bias);
  280. SERIAL_PROTOCOLPGM(" d: "); SERIAL_PROTOCOL(d);
  281. SERIAL_PROTOCOLPGM(" min: "); SERIAL_PROTOCOL(min);
  282. SERIAL_PROTOCOLPGM(" max: "); SERIAL_PROTOCOLLN(max);
  283. if(pid_cycle > 2) {
  284. Ku = (4.0*d)/(3.14159*(max-min)/2.0);
  285. Tu = ((float)(t_low + t_high)/1000.0);
  286. SERIAL_PROTOCOLPGM(" Ku: "); SERIAL_PROTOCOL(Ku);
  287. SERIAL_PROTOCOLPGM(" Tu: "); SERIAL_PROTOCOLLN(Tu);
  288. _Kp = 0.6*Ku;
  289. _Ki = 2*_Kp/Tu;
  290. _Kd = _Kp*Tu/8;
  291. SERIAL_PROTOCOLLNPGM(" Classic PID ");
  292. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  293. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  294. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  295. /*
  296. _Kp = 0.33*Ku;
  297. _Ki = _Kp/Tu;
  298. _Kd = _Kp*Tu/3;
  299. SERIAL_PROTOCOLLNPGM(" Some overshoot ");
  300. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  301. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  302. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  303. _Kp = 0.2*Ku;
  304. _Ki = 2*_Kp/Tu;
  305. _Kd = _Kp*Tu/3;
  306. SERIAL_PROTOCOLLNPGM(" No overshoot ");
  307. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  308. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  309. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  310. */
  311. }
  312. }
  313. if (extruder<0)
  314. {
  315. soft_pwm_bed = (bias + d) >> 1;
  316. timer02_set_pwm0(soft_pwm_bed << 1);
  317. }
  318. else
  319. soft_pwm[extruder] = (bias + d) >> 1;
  320. pid_cycle++;
  321. min=temp;
  322. }
  323. }
  324. }
  325. if(input > (temp + 20)) {
  326. SERIAL_PROTOCOLLNPGM("PID Autotune failed! Temperature too high");
  327. pid_tuning_finished = true;
  328. pid_cycle = 0;
  329. return;
  330. }
  331. if(_millis() - temp_millis > 2000) {
  332. int p;
  333. if (extruder<0){
  334. p=soft_pwm_bed;
  335. SERIAL_PROTOCOLPGM("B:");
  336. }else{
  337. p=soft_pwm[extruder];
  338. SERIAL_PROTOCOLPGM("T:");
  339. }
  340. SERIAL_PROTOCOL(input);
  341. SERIAL_PROTOCOLPGM(" @:");
  342. SERIAL_PROTOCOLLN(p);
  343. if (safety_check_cycles == 0) { //save ambient temp
  344. temp_ambient = input;
  345. //SERIAL_ECHOPGM("Ambient T: ");
  346. //MYSERIAL.println(temp_ambient);
  347. safety_check_cycles++;
  348. }
  349. else if (safety_check_cycles < safety_check_cycles_count) { //delay
  350. safety_check_cycles++;
  351. }
  352. else if (safety_check_cycles == safety_check_cycles_count){ //check that temperature is rising
  353. safety_check_cycles++;
  354. //SERIAL_ECHOPGM("Time from beginning: ");
  355. //MYSERIAL.print(safety_check_cycles_count * 2);
  356. //SERIAL_ECHOPGM("s. Difference between current and ambient T: ");
  357. //MYSERIAL.println(input - temp_ambient);
  358. if (fabs(input - temp_ambient) < 5.0) {
  359. temp_runaway_stop(false, (extruder<0));
  360. pid_tuning_finished = true;
  361. return;
  362. }
  363. }
  364. temp_millis = _millis();
  365. }
  366. if(((_millis() - t1) + (_millis() - t2)) > (10L*60L*1000L*2L)) {
  367. SERIAL_PROTOCOLLNPGM("PID Autotune failed! timeout");
  368. pid_tuning_finished = true;
  369. pid_cycle = 0;
  370. return;
  371. }
  372. if(pid_cycle > ncycles) {
  373. SERIAL_PROTOCOLLNPGM("PID Autotune finished! Put the last Kp, Ki and Kd constants from above into Configuration.h");
  374. pid_tuning_finished = true;
  375. pid_cycle = 0;
  376. return;
  377. }
  378. lcd_update(0);
  379. }
  380. }
  381. void updatePID()
  382. {
  383. // TODO: iState_sum_max and PID values should be synchronized for temp_mgr_isr
  384. #ifdef PIDTEMP
  385. for(uint_least8_t e = 0; e < EXTRUDERS; e++) {
  386. iState_sum_max[e] = PID_INTEGRAL_DRIVE_MAX / cs.Ki;
  387. }
  388. #endif
  389. #ifdef PIDTEMPBED
  390. temp_iState_max_bed = PID_INTEGRAL_DRIVE_MAX / cs.bedKi;
  391. #endif
  392. }
  393. int getHeaterPower(int heater) {
  394. if (heater<0)
  395. return soft_pwm_bed;
  396. return soft_pwm[heater];
  397. }
  398. // reset PID state after changing target_temperature
  399. void resetPID(uint8_t extruder _UNUSED) {}
  400. enum class TempErrorSource : uint8_t
  401. {
  402. hotend,
  403. bed,
  404. #ifdef AMBIENT_THERMISTOR
  405. ambient,
  406. #endif
  407. };
  408. // thermal error type (in order of decreasing priority!)
  409. enum class TempErrorType : uint8_t
  410. {
  411. max,
  412. min,
  413. preheat,
  414. runaway,
  415. #ifdef TEMP_MODEL
  416. model,
  417. #endif
  418. };
  419. // error state (updated via set_temp_error from isr context)
  420. volatile static union
  421. {
  422. uint8_t v;
  423. struct
  424. {
  425. uint8_t error: 1; // error condition
  426. uint8_t assert: 1; // error is still asserted
  427. uint8_t source: 2; // source
  428. uint8_t index: 1; // source index
  429. uint8_t type: 3; // error type
  430. };
  431. } temp_error_state;
  432. // set the error type from within the temp_mgr isr to be handled in manager_heater
  433. // - immediately disable all heaters and turn on all fans at full speed
  434. // - prevent the user to set temperatures until all errors are cleared
  435. void set_temp_error(TempErrorSource source, uint8_t index, TempErrorType type)
  436. {
  437. // save the original target temperatures for recovery before disabling heaters
  438. if(!temp_error_state.error) {
  439. saved_bed_temperature = target_temperature_bed;
  440. saved_extruder_temperature = target_temperature[index];
  441. saved_fan_speed = fanSpeed;
  442. }
  443. // keep disabling heaters and keep fans on as long as the condition is asserted
  444. disable_heater();
  445. hotendFanSetFullSpeed();
  446. // set the initial error source to the highest priority error
  447. if(!temp_error_state.error || (uint8_t)type < temp_error_state.type) {
  448. temp_error_state.source = (uint8_t)source;
  449. temp_error_state.index = index;
  450. temp_error_state.type = (uint8_t)type;
  451. }
  452. // always set the error state
  453. temp_error_state.error = true;
  454. temp_error_state.assert = true;
  455. }
  456. bool get_temp_error()
  457. {
  458. return temp_error_state.v;
  459. }
  460. void handle_temp_error();
  461. void manage_heater()
  462. {
  463. #ifdef WATCHDOG
  464. wdt_reset();
  465. #endif //WATCHDOG
  466. // limit execution to the same rate as temp_mgr (low-level fault handling is already handled -
  467. // any remaining error handling is just user-facing and can wait one extra cycle)
  468. if(!temp_meas_ready)
  469. return;
  470. // syncronize temperatures with isr
  471. updateTemperatures();
  472. #ifdef TEMP_MODEL
  473. // handle model warnings first, so not to override the error handler
  474. if(temp_model::warning_state.warning)
  475. temp_model::handle_warning();
  476. #endif
  477. // handle temperature errors
  478. if(temp_error_state.v)
  479. handle_temp_error();
  480. // periodically check fans
  481. checkFans();
  482. #ifdef TEMP_MODEL_DEBUG
  483. temp_model::log_usr();
  484. #endif
  485. }
  486. #define PGM_RD_W(x) (short)pgm_read_word(&x)
  487. // Derived from RepRap FiveD extruder::getTemperature()
  488. // For hot end temperature measurement.
  489. static float analog2temp(int raw, uint8_t e) {
  490. if(e >= EXTRUDERS)
  491. {
  492. SERIAL_ERROR_START;
  493. SERIAL_ERROR((int)e);
  494. SERIAL_ERRORLNPGM(" - Invalid extruder number !");
  495. kill(NULL, 6);
  496. return 0.0;
  497. }
  498. #ifdef HEATER_0_USES_MAX6675
  499. if (e == 0)
  500. {
  501. return 0.25 * raw;
  502. }
  503. #endif
  504. if(heater_ttbl_map[e] != NULL)
  505. {
  506. float celsius = 0;
  507. uint8_t i;
  508. short (*tt)[][2] = (short (*)[][2])(heater_ttbl_map[e]);
  509. for (i=1; i<heater_ttbllen_map[e]; i++)
  510. {
  511. if (PGM_RD_W((*tt)[i][0]) > raw)
  512. {
  513. celsius = PGM_RD_W((*tt)[i-1][1]) +
  514. (raw - PGM_RD_W((*tt)[i-1][0])) *
  515. (float)(PGM_RD_W((*tt)[i][1]) - PGM_RD_W((*tt)[i-1][1])) /
  516. (float)(PGM_RD_W((*tt)[i][0]) - PGM_RD_W((*tt)[i-1][0]));
  517. break;
  518. }
  519. }
  520. // Overflow: Set to last value in the table
  521. if (i == heater_ttbllen_map[e]) celsius = PGM_RD_W((*tt)[i-1][1]);
  522. return celsius;
  523. }
  524. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET;
  525. }
  526. // Derived from RepRap FiveD extruder::getTemperature()
  527. // For bed temperature measurement.
  528. static float analog2tempBed(int raw) {
  529. #ifdef BED_USES_THERMISTOR
  530. float celsius = 0;
  531. byte i;
  532. for (i=1; i<BEDTEMPTABLE_LEN; i++)
  533. {
  534. if (PGM_RD_W(BEDTEMPTABLE[i][0]) > raw)
  535. {
  536. celsius = PGM_RD_W(BEDTEMPTABLE[i-1][1]) +
  537. (raw - PGM_RD_W(BEDTEMPTABLE[i-1][0])) *
  538. (float)(PGM_RD_W(BEDTEMPTABLE[i][1]) - PGM_RD_W(BEDTEMPTABLE[i-1][1])) /
  539. (float)(PGM_RD_W(BEDTEMPTABLE[i][0]) - PGM_RD_W(BEDTEMPTABLE[i-1][0]));
  540. break;
  541. }
  542. }
  543. // Overflow: Set to last value in the table
  544. if (i == BEDTEMPTABLE_LEN) celsius = PGM_RD_W(BEDTEMPTABLE[i-1][1]);
  545. // temperature offset adjustment
  546. #ifdef BED_OFFSET
  547. float _offset = BED_OFFSET;
  548. float _offset_center = BED_OFFSET_CENTER;
  549. float _offset_start = BED_OFFSET_START;
  550. float _first_koef = (_offset / 2) / (_offset_center - _offset_start);
  551. float _second_koef = (_offset / 2) / (100 - _offset_center);
  552. if (celsius >= _offset_start && celsius <= _offset_center)
  553. {
  554. celsius = celsius + (_first_koef * (celsius - _offset_start));
  555. }
  556. else if (celsius > _offset_center && celsius <= 100)
  557. {
  558. celsius = celsius + (_first_koef * (_offset_center - _offset_start)) + ( _second_koef * ( celsius - ( 100 - _offset_center ) )) ;
  559. }
  560. else if (celsius > 100)
  561. {
  562. celsius = celsius + _offset;
  563. }
  564. #endif
  565. return celsius;
  566. #elif defined BED_USES_AD595
  567. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET;
  568. #else
  569. return 0;
  570. #endif
  571. }
  572. #ifdef AMBIENT_THERMISTOR
  573. static float analog2tempAmbient(int raw)
  574. {
  575. float celsius = 0;
  576. byte i;
  577. for (i=1; i<AMBIENTTEMPTABLE_LEN; i++)
  578. {
  579. if (PGM_RD_W(AMBIENTTEMPTABLE[i][0]) > raw)
  580. {
  581. celsius = PGM_RD_W(AMBIENTTEMPTABLE[i-1][1]) +
  582. (raw - PGM_RD_W(AMBIENTTEMPTABLE[i-1][0])) *
  583. (float)(PGM_RD_W(AMBIENTTEMPTABLE[i][1]) - PGM_RD_W(AMBIENTTEMPTABLE[i-1][1])) /
  584. (float)(PGM_RD_W(AMBIENTTEMPTABLE[i][0]) - PGM_RD_W(AMBIENTTEMPTABLE[i-1][0]));
  585. break;
  586. }
  587. }
  588. // Overflow: Set to last value in the table
  589. if (i == AMBIENTTEMPTABLE_LEN) celsius = PGM_RD_W(AMBIENTTEMPTABLE[i-1][1]);
  590. return celsius;
  591. }
  592. #endif //AMBIENT_THERMISTOR
  593. void soft_pwm_init()
  594. {
  595. #if MB(RUMBA) && ((TEMP_SENSOR_0==-1)||(TEMP_SENSOR_1==-1)||(TEMP_SENSOR_2==-1)||(TEMP_SENSOR_BED==-1))
  596. //disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
  597. MCUCR=(1<<JTD);
  598. MCUCR=(1<<JTD);
  599. #endif
  600. // Finish init of mult extruder arrays
  601. for(int e = 0; e < EXTRUDERS; e++) {
  602. // populate with the first value
  603. maxttemp[e] = maxttemp[0];
  604. #ifdef PIDTEMP
  605. iState_sum_min[e] = 0.0;
  606. iState_sum_max[e] = PID_INTEGRAL_DRIVE_MAX / cs.Ki;
  607. #endif //PIDTEMP
  608. #ifdef PIDTEMPBED
  609. temp_iState_min_bed = 0.0;
  610. temp_iState_max_bed = PID_INTEGRAL_DRIVE_MAX / cs.bedKi;
  611. #endif //PIDTEMPBED
  612. }
  613. #if defined(HEATER_0_PIN) && (HEATER_0_PIN > -1)
  614. SET_OUTPUT(HEATER_0_PIN);
  615. #endif
  616. #if defined(HEATER_1_PIN) && (HEATER_1_PIN > -1)
  617. SET_OUTPUT(HEATER_1_PIN);
  618. #endif
  619. #if defined(HEATER_2_PIN) && (HEATER_2_PIN > -1)
  620. SET_OUTPUT(HEATER_2_PIN);
  621. #endif
  622. #if defined(HEATER_BED_PIN) && (HEATER_BED_PIN > -1)
  623. SET_OUTPUT(HEATER_BED_PIN);
  624. #endif
  625. #if defined(FAN_PIN) && (FAN_PIN > -1)
  626. SET_OUTPUT(FAN_PIN);
  627. #ifdef FAST_PWM_FAN
  628. setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  629. #endif
  630. #ifdef FAN_SOFT_PWM
  631. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  632. #endif
  633. #endif
  634. #ifdef HEATER_0_USES_MAX6675
  635. #ifndef SDSUPPORT
  636. SET_OUTPUT(SCK_PIN);
  637. WRITE(SCK_PIN,0);
  638. SET_OUTPUT(MOSI_PIN);
  639. WRITE(MOSI_PIN,1);
  640. SET_INPUT(MISO_PIN);
  641. WRITE(MISO_PIN,1);
  642. #endif
  643. /* Using pinMode and digitalWrite, as that was the only way I could get it to compile */
  644. //Have to toggle SD card CS pin to low first, to enable firmware to talk with SD card
  645. pinMode(SS_PIN, OUTPUT);
  646. digitalWrite(SS_PIN,0);
  647. pinMode(MAX6675_SS, OUTPUT);
  648. digitalWrite(MAX6675_SS,1);
  649. #endif
  650. #ifdef HEATER_0_MINTEMP
  651. minttemp[0] = HEATER_0_MINTEMP;
  652. while(analog2temp(minttemp_raw[0], 0) < HEATER_0_MINTEMP) {
  653. #if HEATER_0_RAW_LO_TEMP < HEATER_0_RAW_HI_TEMP
  654. minttemp_raw[0] += OVERSAMPLENR;
  655. #else
  656. minttemp_raw[0] -= OVERSAMPLENR;
  657. #endif
  658. }
  659. #endif //MINTEMP
  660. #ifdef HEATER_0_MAXTEMP
  661. maxttemp[0] = HEATER_0_MAXTEMP;
  662. while(analog2temp(maxttemp_raw[0], 0) > HEATER_0_MAXTEMP) {
  663. #if HEATER_0_RAW_LO_TEMP < HEATER_0_RAW_HI_TEMP
  664. maxttemp_raw[0] -= OVERSAMPLENR;
  665. #else
  666. maxttemp_raw[0] += OVERSAMPLENR;
  667. #endif
  668. }
  669. #endif //MAXTEMP
  670. #if (EXTRUDERS > 1) && defined(HEATER_1_MINTEMP)
  671. minttemp[1] = HEATER_1_MINTEMP;
  672. while(analog2temp(minttemp_raw[1], 1) < HEATER_1_MINTEMP) {
  673. #if HEATER_1_RAW_LO_TEMP < HEATER_1_RAW_HI_TEMP
  674. minttemp_raw[1] += OVERSAMPLENR;
  675. #else
  676. minttemp_raw[1] -= OVERSAMPLENR;
  677. #endif
  678. }
  679. #endif // MINTEMP 1
  680. #if (EXTRUDERS > 1) && defined(HEATER_1_MAXTEMP)
  681. maxttemp[1] = HEATER_1_MAXTEMP;
  682. while(analog2temp(maxttemp_raw[1], 1) > HEATER_1_MAXTEMP) {
  683. #if HEATER_1_RAW_LO_TEMP < HEATER_1_RAW_HI_TEMP
  684. maxttemp_raw[1] -= OVERSAMPLENR;
  685. #else
  686. maxttemp_raw[1] += OVERSAMPLENR;
  687. #endif
  688. }
  689. #endif //MAXTEMP 1
  690. #if (EXTRUDERS > 2) && defined(HEATER_2_MINTEMP)
  691. minttemp[2] = HEATER_2_MINTEMP;
  692. while(analog2temp(minttemp_raw[2], 2) < HEATER_2_MINTEMP) {
  693. #if HEATER_2_RAW_LO_TEMP < HEATER_2_RAW_HI_TEMP
  694. minttemp_raw[2] += OVERSAMPLENR;
  695. #else
  696. minttemp_raw[2] -= OVERSAMPLENR;
  697. #endif
  698. }
  699. #endif //MINTEMP 2
  700. #if (EXTRUDERS > 2) && defined(HEATER_2_MAXTEMP)
  701. maxttemp[2] = HEATER_2_MAXTEMP;
  702. while(analog2temp(maxttemp_raw[2], 2) > HEATER_2_MAXTEMP) {
  703. #if HEATER_2_RAW_LO_TEMP < HEATER_2_RAW_HI_TEMP
  704. maxttemp_raw[2] -= OVERSAMPLENR;
  705. #else
  706. maxttemp_raw[2] += OVERSAMPLENR;
  707. #endif
  708. }
  709. #endif //MAXTEMP 2
  710. #ifdef BED_MINTEMP
  711. while(analog2tempBed(bed_minttemp_raw) < BED_MINTEMP) {
  712. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  713. bed_minttemp_raw += OVERSAMPLENR;
  714. #else
  715. bed_minttemp_raw -= OVERSAMPLENR;
  716. #endif
  717. }
  718. #endif //BED_MINTEMP
  719. #ifdef BED_MAXTEMP
  720. while(analog2tempBed(bed_maxttemp_raw) > BED_MAXTEMP) {
  721. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  722. bed_maxttemp_raw -= OVERSAMPLENR;
  723. #else
  724. bed_maxttemp_raw += OVERSAMPLENR;
  725. #endif
  726. }
  727. #endif //BED_MAXTEMP
  728. #ifdef AMBIENT_MINTEMP
  729. while(analog2tempAmbient(ambient_minttemp_raw) < AMBIENT_MINTEMP) {
  730. #if AMBIENT_RAW_LO_TEMP < AMBIENT_RAW_HI_TEMP
  731. ambient_minttemp_raw += OVERSAMPLENR;
  732. #else
  733. ambient_minttemp_raw -= OVERSAMPLENR;
  734. #endif
  735. }
  736. #endif //AMBIENT_MINTEMP
  737. #ifdef AMBIENT_MAXTEMP
  738. while(analog2tempAmbient(ambient_maxttemp_raw) > AMBIENT_MAXTEMP) {
  739. #if AMBIENT_RAW_LO_TEMP < AMBIENT_RAW_HI_TEMP
  740. ambient_maxttemp_raw -= OVERSAMPLENR;
  741. #else
  742. ambient_maxttemp_raw += OVERSAMPLENR;
  743. #endif
  744. }
  745. #endif //AMBIENT_MAXTEMP
  746. timer0_init(); //enables the heatbed timer.
  747. // timer2 already enabled earlier in the code
  748. // now enable the COMPB temperature interrupt
  749. OCR2B = 128;
  750. ENABLE_SOFT_PWM_INTERRUPT();
  751. timer4_init(); //for tone and Extruder fan PWM
  752. }
  753. #if (defined (TEMP_RUNAWAY_BED_HYSTERESIS) && TEMP_RUNAWAY_BED_TIMEOUT > 0) || (defined (TEMP_RUNAWAY_EXTRUDER_HYSTERESIS) && TEMP_RUNAWAY_EXTRUDER_TIMEOUT > 0)
  754. static void temp_runaway_check(uint8_t _heater_id, float _target_temperature, float _current_temperature, float _output, bool _isbed)
  755. {
  756. float __delta;
  757. float __hysteresis = 0;
  758. uint16_t __timeout = 0;
  759. bool temp_runaway_check_active = false;
  760. static float __preheat_start[2] = { 0,0}; //currently just bed and one extruder
  761. static uint8_t __preheat_counter[2] = { 0,0};
  762. static uint8_t __preheat_errors[2] = { 0,0};
  763. if (_millis() - temp_runaway_timer[_heater_id] > 2000)
  764. {
  765. #ifdef TEMP_RUNAWAY_BED_TIMEOUT
  766. if (_isbed)
  767. {
  768. __hysteresis = TEMP_RUNAWAY_BED_HYSTERESIS;
  769. __timeout = TEMP_RUNAWAY_BED_TIMEOUT;
  770. }
  771. #endif
  772. #ifdef TEMP_RUNAWAY_EXTRUDER_TIMEOUT
  773. if (!_isbed)
  774. {
  775. __hysteresis = TEMP_RUNAWAY_EXTRUDER_HYSTERESIS;
  776. __timeout = TEMP_RUNAWAY_EXTRUDER_TIMEOUT;
  777. }
  778. #endif
  779. temp_runaway_timer[_heater_id] = _millis();
  780. if (_output == 0)
  781. {
  782. temp_runaway_check_active = false;
  783. temp_runaway_error_counter[_heater_id] = 0;
  784. }
  785. if (temp_runaway_target[_heater_id] != _target_temperature)
  786. {
  787. if (_target_temperature > 0)
  788. {
  789. temp_runaway_status[_heater_id] = TempRunaway_PREHEAT;
  790. temp_runaway_target[_heater_id] = _target_temperature;
  791. __preheat_start[_heater_id] = _current_temperature;
  792. __preheat_counter[_heater_id] = 0;
  793. }
  794. else
  795. {
  796. temp_runaway_status[_heater_id] = TempRunaway_INACTIVE;
  797. temp_runaway_target[_heater_id] = _target_temperature;
  798. }
  799. }
  800. if ((_current_temperature < _target_temperature) && (temp_runaway_status[_heater_id] == TempRunaway_PREHEAT))
  801. {
  802. __preheat_counter[_heater_id]++;
  803. if (__preheat_counter[_heater_id] > ((_isbed) ? 16 : 8)) // periodicaly check if current temperature changes
  804. {
  805. /*SERIAL_ECHOPGM("Heater:");
  806. MYSERIAL.print(_heater_id);
  807. SERIAL_ECHOPGM(" T:");
  808. MYSERIAL.print(_current_temperature);
  809. SERIAL_ECHOPGM(" Tstart:");
  810. MYSERIAL.print(__preheat_start[_heater_id]);
  811. SERIAL_ECHOPGM(" delta:");
  812. MYSERIAL.print(_current_temperature-__preheat_start[_heater_id]);*/
  813. //-// if (_current_temperature - __preheat_start[_heater_id] < 2) {
  814. //-// if (_current_temperature - __preheat_start[_heater_id] < ((_isbed && (_current_temperature>105.0))?0.6:2.0)) {
  815. __delta=2.0;
  816. if(_isbed)
  817. {
  818. __delta=3.0;
  819. if(_current_temperature>90.0) __delta=2.0;
  820. if(_current_temperature>105.0) __delta=0.6;
  821. }
  822. if (_current_temperature - __preheat_start[_heater_id] < __delta) {
  823. __preheat_errors[_heater_id]++;
  824. /*SERIAL_ECHOPGM(" Preheat errors:");
  825. MYSERIAL.println(__preheat_errors[_heater_id]);*/
  826. }
  827. else {
  828. //SERIAL_ECHOLNPGM("");
  829. __preheat_errors[_heater_id] = 0;
  830. }
  831. if (__preheat_errors[_heater_id] > ((_isbed) ? 3 : 5))
  832. set_temp_error((_isbed?TempErrorSource::bed:TempErrorSource::hotend), _heater_id, TempErrorType::preheat);
  833. __preheat_start[_heater_id] = _current_temperature;
  834. __preheat_counter[_heater_id] = 0;
  835. }
  836. }
  837. //-// if (_current_temperature >= _target_temperature && temp_runaway_status[_heater_id] == TempRunaway_PREHEAT)
  838. if ((_current_temperature > (_target_temperature - __hysteresis)) && temp_runaway_status[_heater_id] == TempRunaway_PREHEAT)
  839. {
  840. /*SERIAL_ECHOPGM("Heater:");
  841. MYSERIAL.print(_heater_id);
  842. MYSERIAL.println(" ->tempRunaway");*/
  843. temp_runaway_status[_heater_id] = TempRunaway_ACTIVE;
  844. temp_runaway_check_active = false;
  845. temp_runaway_error_counter[_heater_id] = 0;
  846. }
  847. if (_output > 0)
  848. {
  849. temp_runaway_check_active = true;
  850. }
  851. if (temp_runaway_check_active)
  852. {
  853. // we are in range
  854. if ((_current_temperature > (_target_temperature - __hysteresis)) && (_current_temperature < (_target_temperature + __hysteresis)))
  855. {
  856. temp_runaway_check_active = false;
  857. temp_runaway_error_counter[_heater_id] = 0;
  858. }
  859. else
  860. {
  861. if (temp_runaway_status[_heater_id] > TempRunaway_PREHEAT)
  862. {
  863. temp_runaway_error_counter[_heater_id]++;
  864. if (temp_runaway_error_counter[_heater_id] * 2 > __timeout)
  865. set_temp_error((_isbed?TempErrorSource::bed:TempErrorSource::hotend), _heater_id, TempErrorType::runaway);
  866. }
  867. }
  868. }
  869. }
  870. }
  871. static void temp_runaway_stop(bool isPreheat, bool isBed)
  872. {
  873. if(IsStopped() == false) {
  874. if (isPreheat) {
  875. lcd_setalertstatuspgm(isBed? PSTR("BED PREHEAT ERROR") : PSTR("PREHEAT ERROR"), LCD_STATUS_CRITICAL);
  876. SERIAL_ERROR_START;
  877. if (isBed) {
  878. SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HEATBED)");
  879. } else {
  880. SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HOTEND)");
  881. }
  882. } else {
  883. lcd_setalertstatuspgm(isBed? PSTR("BED THERMAL RUNAWAY") : PSTR("THERMAL RUNAWAY"), LCD_STATUS_CRITICAL);
  884. SERIAL_ERROR_START;
  885. if (isBed) {
  886. SERIAL_ERRORLNPGM(" HEATBED THERMAL RUNAWAY");
  887. } else {
  888. SERIAL_ERRORLNPGM(" HOTEND THERMAL RUNAWAY");
  889. }
  890. }
  891. if (farm_mode) {
  892. prusa_statistics(0);
  893. prusa_statistics(isPreheat? 91 : 90);
  894. }
  895. }
  896. ThermalStop();
  897. }
  898. #endif
  899. //! codes of alert messages for the LCD - it is shorter to compare an uin8_t
  900. //! than raw const char * of the messages themselves.
  901. //! Could be used for MAXTEMP situations too - after reaching MAXTEMP and turning off the heater automagically
  902. //! the heater/bed may cool down and a similar alert message like "MAXTERM fixed..." may be displayed.
  903. enum { LCDALERT_NONE = 0, LCDALERT_HEATERMINTEMP, LCDALERT_BEDMINTEMP, LCDALERT_MINTEMPFIXED, LCDALERT_PLEASERESTART };
  904. //! remember the last alert message sent to the LCD
  905. //! to prevent flicker and improve speed
  906. static uint8_t last_alert_sent_to_lcd = LCDALERT_NONE;
  907. //! update the current temperature error message
  908. //! @param type short error abbreviation (PROGMEM)
  909. static void temp_update_messagepgm(const char* PROGMEM type)
  910. {
  911. char msg[LCD_WIDTH];
  912. strcpy_P(msg, PSTR("Err: "));
  913. strcat_P(msg, type);
  914. lcd_setalertstatus(msg, LCD_STATUS_CRITICAL);
  915. }
  916. //! signal a temperature error on both the lcd and serial
  917. //! @param type short error abbreviation (PROGMEM)
  918. //! @param e optional extruder index for hotend errors
  919. static void temp_error_messagepgm(const char* PROGMEM type, uint8_t e = EXTRUDERS)
  920. {
  921. temp_update_messagepgm(type);
  922. SERIAL_ERROR_START;
  923. if(e != EXTRUDERS) {
  924. SERIAL_ERROR((int)e);
  925. SERIAL_ERRORPGM(": ");
  926. }
  927. SERIAL_ERRORPGM("Heaters switched off. ");
  928. SERIAL_ERRORRPGM(type);
  929. SERIAL_ERRORLNPGM(" triggered!");
  930. }
  931. static void max_temp_error(uint8_t e) {
  932. if(IsStopped() == false) {
  933. temp_error_messagepgm(PSTR("MAXTEMP"), e);
  934. if (farm_mode) prusa_statistics(93);
  935. }
  936. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  937. ThermalStop();
  938. #endif
  939. }
  940. static void min_temp_error(uint8_t e) {
  941. static const char err[] PROGMEM = "MINTEMP";
  942. if(IsStopped() == false) {
  943. temp_error_messagepgm(err, e);
  944. last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  945. if (farm_mode) prusa_statistics(92);
  946. } else if( last_alert_sent_to_lcd != LCDALERT_HEATERMINTEMP ){ // only update, if the lcd message is to be changed (i.e. not the same as last time)
  947. // we are already stopped due to some error, only update the status message without flickering
  948. temp_update_messagepgm(err);
  949. last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  950. }
  951. ThermalStop();
  952. }
  953. static void bed_max_temp_error(void) {
  954. if(IsStopped() == false) {
  955. temp_error_messagepgm(PSTR("MAXTEMP BED"));
  956. }
  957. ThermalStop();
  958. }
  959. static void bed_min_temp_error(void) {
  960. static const char err[] PROGMEM = "MINTEMP BED";
  961. if(IsStopped() == false) {
  962. temp_error_messagepgm(err);
  963. last_alert_sent_to_lcd = LCDALERT_BEDMINTEMP;
  964. } else if( last_alert_sent_to_lcd != LCDALERT_BEDMINTEMP ){ // only update, if the lcd message is to be changed (i.e. not the same as last time)
  965. // we are already stopped due to some error, only update the status message without flickering
  966. temp_update_messagepgm(err);
  967. last_alert_sent_to_lcd = LCDALERT_BEDMINTEMP;
  968. }
  969. ThermalStop();
  970. }
  971. #ifdef AMBIENT_THERMISTOR
  972. static void ambient_max_temp_error(void) {
  973. if(IsStopped() == false) {
  974. temp_error_messagepgm(PSTR("MAXTEMP AMB"));
  975. }
  976. ThermalStop();
  977. }
  978. static void ambient_min_temp_error(void) {
  979. if(IsStopped() == false) {
  980. temp_error_messagepgm(PSTR("MINTEMP AMB"));
  981. }
  982. ThermalStop();
  983. }
  984. #endif
  985. #ifdef HEATER_0_USES_MAX6675
  986. #define MAX6675_HEAT_INTERVAL 250
  987. long max6675_previous_millis = MAX6675_HEAT_INTERVAL;
  988. int max6675_temp = 2000;
  989. int read_max6675()
  990. {
  991. if (_millis() - max6675_previous_millis < MAX6675_HEAT_INTERVAL)
  992. return max6675_temp;
  993. max6675_previous_millis = _millis();
  994. max6675_temp = 0;
  995. #ifdef PRR
  996. PRR &= ~(1<<PRSPI);
  997. #elif defined PRR0
  998. PRR0 &= ~(1<<PRSPI);
  999. #endif
  1000. SPCR = (1<<MSTR) | (1<<SPE) | (1<<SPR0);
  1001. // enable TT_MAX6675
  1002. WRITE(MAX6675_SS, 0);
  1003. // ensure 100ns delay - a bit extra is fine
  1004. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1005. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1006. // read MSB
  1007. SPDR = 0;
  1008. for (;(SPSR & (1<<SPIF)) == 0;);
  1009. max6675_temp = SPDR;
  1010. max6675_temp <<= 8;
  1011. // read LSB
  1012. SPDR = 0;
  1013. for (;(SPSR & (1<<SPIF)) == 0;);
  1014. max6675_temp |= SPDR;
  1015. // disable TT_MAX6675
  1016. WRITE(MAX6675_SS, 1);
  1017. if (max6675_temp & 4)
  1018. {
  1019. // thermocouple open
  1020. max6675_temp = 2000;
  1021. }
  1022. else
  1023. {
  1024. max6675_temp = max6675_temp >> 3;
  1025. }
  1026. return max6675_temp;
  1027. }
  1028. #endif
  1029. #ifdef BABYSTEPPING
  1030. FORCE_INLINE static void applyBabysteps() {
  1031. for(uint8_t axis=0;axis<3;axis++)
  1032. {
  1033. int curTodo=babystepsTodo[axis]; //get rid of volatile for performance
  1034. if(curTodo>0)
  1035. {
  1036. CRITICAL_SECTION_START;
  1037. babystep(axis,/*fwd*/true);
  1038. babystepsTodo[axis]--; //less to do next time
  1039. CRITICAL_SECTION_END;
  1040. }
  1041. else
  1042. if(curTodo<0)
  1043. {
  1044. CRITICAL_SECTION_START;
  1045. babystep(axis,/*fwd*/false);
  1046. babystepsTodo[axis]++; //less to do next time
  1047. CRITICAL_SECTION_END;
  1048. }
  1049. }
  1050. }
  1051. #endif //BABYSTEPPING
  1052. FORCE_INLINE static void soft_pwm_core()
  1053. {
  1054. static uint8_t pwm_count = (1 << SOFT_PWM_SCALE);
  1055. static uint8_t soft_pwm_0;
  1056. #ifdef SLOW_PWM_HEATERS
  1057. static unsigned char slow_pwm_count = 0;
  1058. static unsigned char state_heater_0 = 0;
  1059. static unsigned char state_timer_heater_0 = 0;
  1060. #endif
  1061. #if (EXTRUDERS > 1) || defined(HEATERS_PARALLEL)
  1062. static unsigned char soft_pwm_1;
  1063. #ifdef SLOW_PWM_HEATERS
  1064. static unsigned char state_heater_1 = 0;
  1065. static unsigned char state_timer_heater_1 = 0;
  1066. #endif
  1067. #endif
  1068. #if EXTRUDERS > 2
  1069. static unsigned char soft_pwm_2;
  1070. #ifdef SLOW_PWM_HEATERS
  1071. static unsigned char state_heater_2 = 0;
  1072. static unsigned char state_timer_heater_2 = 0;
  1073. #endif
  1074. #endif
  1075. #if HEATER_BED_PIN > -1
  1076. // @@DR static unsigned char soft_pwm_b;
  1077. #ifdef SLOW_PWM_HEATERS
  1078. static unsigned char state_heater_b = 0;
  1079. static unsigned char state_timer_heater_b = 0;
  1080. #endif
  1081. #endif
  1082. #if defined(FILWIDTH_PIN) &&(FILWIDTH_PIN > -1)
  1083. static unsigned long raw_filwidth_value = 0; //added for filament width sensor
  1084. #endif
  1085. #ifndef SLOW_PWM_HEATERS
  1086. /*
  1087. * standard PWM modulation
  1088. */
  1089. if (pwm_count == 0)
  1090. {
  1091. soft_pwm_0 = soft_pwm[0];
  1092. if(soft_pwm_0 > 0)
  1093. {
  1094. WRITE(HEATER_0_PIN,1);
  1095. #ifdef HEATERS_PARALLEL
  1096. WRITE(HEATER_1_PIN,1);
  1097. #endif
  1098. } else WRITE(HEATER_0_PIN,0);
  1099. #if EXTRUDERS > 1
  1100. soft_pwm_1 = soft_pwm[1];
  1101. if(soft_pwm_1 > 0) WRITE(HEATER_1_PIN,1); else WRITE(HEATER_1_PIN,0);
  1102. #endif
  1103. #if EXTRUDERS > 2
  1104. soft_pwm_2 = soft_pwm[2];
  1105. if(soft_pwm_2 > 0) WRITE(HEATER_2_PIN,1); else WRITE(HEATER_2_PIN,0);
  1106. #endif
  1107. }
  1108. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1109. #if 0 // @@DR vypnuto pro hw pwm bedu
  1110. // tuhle prasarnu bude potreba poustet ve stanovenych intervalech, jinak nemam moc sanci zareagovat
  1111. // teoreticky by se tato cast uz vubec nemusela poustet
  1112. if ((pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1)) == 0)
  1113. {
  1114. soft_pwm_b = soft_pwm_bed >> (7 - HEATER_BED_SOFT_PWM_BITS);
  1115. # ifndef SYSTEM_TIMER_2
  1116. // tady budu krokovat pomalou frekvenci na automatu - tohle je rizeni spinani a rozepinani
  1117. // jako ridici frekvenci mam 2khz, jako vystupni frekvenci mam 30hz
  1118. // 2kHz jsou ovsem ve slysitelnem pasmu, mozna bude potreba jit s frekvenci nahoru (a tomu taky prizpusobit ostatni veci)
  1119. // Teoreticky bych mohl stahnout OCR0B citac na 6, cimz bych se dostal nekam ke 40khz a tady potom honit PWM rychleji nebo i pomaleji
  1120. // to nicemu nevadi. Soft PWM scale by se 20x zvetsilo (no dobre, 16x), cimz by se to posunulo k puvodnimu 30Hz PWM
  1121. //if(soft_pwm_b > 0) WRITE(HEATER_BED_PIN,1); else WRITE(HEATER_BED_PIN,0);
  1122. # endif //SYSTEM_TIMER_2
  1123. }
  1124. #endif
  1125. #endif
  1126. #ifdef FAN_SOFT_PWM
  1127. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1128. {
  1129. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1130. if(soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1131. }
  1132. #endif
  1133. if(soft_pwm_0 < pwm_count)
  1134. {
  1135. WRITE(HEATER_0_PIN,0);
  1136. #ifdef HEATERS_PARALLEL
  1137. WRITE(HEATER_1_PIN,0);
  1138. #endif
  1139. }
  1140. #if EXTRUDERS > 1
  1141. if(soft_pwm_1 < pwm_count) WRITE(HEATER_1_PIN,0);
  1142. #endif
  1143. #if EXTRUDERS > 2
  1144. if(soft_pwm_2 < pwm_count) WRITE(HEATER_2_PIN,0);
  1145. #endif
  1146. #if 0 // @@DR
  1147. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1148. if (soft_pwm_b < (pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1))){
  1149. //WRITE(HEATER_BED_PIN,0);
  1150. }
  1151. //WRITE(HEATER_BED_PIN, pwm_count & 1 );
  1152. #endif
  1153. #endif
  1154. #ifdef FAN_SOFT_PWM
  1155. if (soft_pwm_fan < (pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1))) WRITE(FAN_PIN,0);
  1156. #endif
  1157. pwm_count += (1 << SOFT_PWM_SCALE);
  1158. pwm_count &= 0x7f;
  1159. #else //ifndef SLOW_PWM_HEATERS
  1160. /*
  1161. * SLOW PWM HEATERS
  1162. *
  1163. * for heaters drived by relay
  1164. */
  1165. #ifndef MIN_STATE_TIME
  1166. #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
  1167. #endif
  1168. if (slow_pwm_count == 0) {
  1169. // EXTRUDER 0
  1170. soft_pwm_0 = soft_pwm[0];
  1171. if (soft_pwm_0 > 0) {
  1172. // turn ON heather only if the minimum time is up
  1173. if (state_timer_heater_0 == 0) {
  1174. // if change state set timer
  1175. if (state_heater_0 == 0) {
  1176. state_timer_heater_0 = MIN_STATE_TIME;
  1177. }
  1178. state_heater_0 = 1;
  1179. WRITE(HEATER_0_PIN, 1);
  1180. #ifdef HEATERS_PARALLEL
  1181. WRITE(HEATER_1_PIN, 1);
  1182. #endif
  1183. }
  1184. } else {
  1185. // turn OFF heather only if the minimum time is up
  1186. if (state_timer_heater_0 == 0) {
  1187. // if change state set timer
  1188. if (state_heater_0 == 1) {
  1189. state_timer_heater_0 = MIN_STATE_TIME;
  1190. }
  1191. state_heater_0 = 0;
  1192. WRITE(HEATER_0_PIN, 0);
  1193. #ifdef HEATERS_PARALLEL
  1194. WRITE(HEATER_1_PIN, 0);
  1195. #endif
  1196. }
  1197. }
  1198. #if EXTRUDERS > 1
  1199. // EXTRUDER 1
  1200. soft_pwm_1 = soft_pwm[1];
  1201. if (soft_pwm_1 > 0) {
  1202. // turn ON heather only if the minimum time is up
  1203. if (state_timer_heater_1 == 0) {
  1204. // if change state set timer
  1205. if (state_heater_1 == 0) {
  1206. state_timer_heater_1 = MIN_STATE_TIME;
  1207. }
  1208. state_heater_1 = 1;
  1209. WRITE(HEATER_1_PIN, 1);
  1210. }
  1211. } else {
  1212. // turn OFF heather only if the minimum time is up
  1213. if (state_timer_heater_1 == 0) {
  1214. // if change state set timer
  1215. if (state_heater_1 == 1) {
  1216. state_timer_heater_1 = MIN_STATE_TIME;
  1217. }
  1218. state_heater_1 = 0;
  1219. WRITE(HEATER_1_PIN, 0);
  1220. }
  1221. }
  1222. #endif
  1223. #if EXTRUDERS > 2
  1224. // EXTRUDER 2
  1225. soft_pwm_2 = soft_pwm[2];
  1226. if (soft_pwm_2 > 0) {
  1227. // turn ON heather only if the minimum time is up
  1228. if (state_timer_heater_2 == 0) {
  1229. // if change state set timer
  1230. if (state_heater_2 == 0) {
  1231. state_timer_heater_2 = MIN_STATE_TIME;
  1232. }
  1233. state_heater_2 = 1;
  1234. WRITE(HEATER_2_PIN, 1);
  1235. }
  1236. } else {
  1237. // turn OFF heather only if the minimum time is up
  1238. if (state_timer_heater_2 == 0) {
  1239. // if change state set timer
  1240. if (state_heater_2 == 1) {
  1241. state_timer_heater_2 = MIN_STATE_TIME;
  1242. }
  1243. state_heater_2 = 0;
  1244. WRITE(HEATER_2_PIN, 0);
  1245. }
  1246. }
  1247. #endif
  1248. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1249. // BED
  1250. soft_pwm_b = soft_pwm_bed;
  1251. if (soft_pwm_b > 0) {
  1252. // turn ON heather only if the minimum time is up
  1253. if (state_timer_heater_b == 0) {
  1254. // if change state set timer
  1255. if (state_heater_b == 0) {
  1256. state_timer_heater_b = MIN_STATE_TIME;
  1257. }
  1258. state_heater_b = 1;
  1259. //WRITE(HEATER_BED_PIN, 1);
  1260. }
  1261. } else {
  1262. // turn OFF heather only if the minimum time is up
  1263. if (state_timer_heater_b == 0) {
  1264. // if change state set timer
  1265. if (state_heater_b == 1) {
  1266. state_timer_heater_b = MIN_STATE_TIME;
  1267. }
  1268. state_heater_b = 0;
  1269. WRITE(HEATER_BED_PIN, 0);
  1270. }
  1271. }
  1272. #endif
  1273. } // if (slow_pwm_count == 0)
  1274. // EXTRUDER 0
  1275. if (soft_pwm_0 < slow_pwm_count) {
  1276. // turn OFF heather only if the minimum time is up
  1277. if (state_timer_heater_0 == 0) {
  1278. // if change state set timer
  1279. if (state_heater_0 == 1) {
  1280. state_timer_heater_0 = MIN_STATE_TIME;
  1281. }
  1282. state_heater_0 = 0;
  1283. WRITE(HEATER_0_PIN, 0);
  1284. #ifdef HEATERS_PARALLEL
  1285. WRITE(HEATER_1_PIN, 0);
  1286. #endif
  1287. }
  1288. }
  1289. #if EXTRUDERS > 1
  1290. // EXTRUDER 1
  1291. if (soft_pwm_1 < slow_pwm_count) {
  1292. // turn OFF heather only if the minimum time is up
  1293. if (state_timer_heater_1 == 0) {
  1294. // if change state set timer
  1295. if (state_heater_1 == 1) {
  1296. state_timer_heater_1 = MIN_STATE_TIME;
  1297. }
  1298. state_heater_1 = 0;
  1299. WRITE(HEATER_1_PIN, 0);
  1300. }
  1301. }
  1302. #endif
  1303. #if EXTRUDERS > 2
  1304. // EXTRUDER 2
  1305. if (soft_pwm_2 < slow_pwm_count) {
  1306. // turn OFF heather only if the minimum time is up
  1307. if (state_timer_heater_2 == 0) {
  1308. // if change state set timer
  1309. if (state_heater_2 == 1) {
  1310. state_timer_heater_2 = MIN_STATE_TIME;
  1311. }
  1312. state_heater_2 = 0;
  1313. WRITE(HEATER_2_PIN, 0);
  1314. }
  1315. }
  1316. #endif
  1317. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1318. // BED
  1319. if (soft_pwm_b < slow_pwm_count) {
  1320. // turn OFF heather only if the minimum time is up
  1321. if (state_timer_heater_b == 0) {
  1322. // if change state set timer
  1323. if (state_heater_b == 1) {
  1324. state_timer_heater_b = MIN_STATE_TIME;
  1325. }
  1326. state_heater_b = 0;
  1327. WRITE(HEATER_BED_PIN, 0);
  1328. }
  1329. }
  1330. #endif
  1331. #ifdef FAN_SOFT_PWM
  1332. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1333. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1334. if (soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1335. }
  1336. if (soft_pwm_fan < pwm_count) WRITE(FAN_PIN,0);
  1337. #endif
  1338. pwm_count += (1 << SOFT_PWM_SCALE);
  1339. pwm_count &= 0x7f;
  1340. // increment slow_pwm_count only every 64 pwm_count circa 65.5ms
  1341. if ((pwm_count % 64) == 0) {
  1342. slow_pwm_count++;
  1343. slow_pwm_count &= 0x7f;
  1344. // Extruder 0
  1345. if (state_timer_heater_0 > 0) {
  1346. state_timer_heater_0--;
  1347. }
  1348. #if EXTRUDERS > 1
  1349. // Extruder 1
  1350. if (state_timer_heater_1 > 0)
  1351. state_timer_heater_1--;
  1352. #endif
  1353. #if EXTRUDERS > 2
  1354. // Extruder 2
  1355. if (state_timer_heater_2 > 0)
  1356. state_timer_heater_2--;
  1357. #endif
  1358. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1359. // Bed
  1360. if (state_timer_heater_b > 0)
  1361. state_timer_heater_b--;
  1362. #endif
  1363. } //if ((pwm_count % 64) == 0) {
  1364. #endif //ifndef SLOW_PWM_HEATERS
  1365. }
  1366. FORCE_INLINE static void soft_pwm_isr()
  1367. {
  1368. lcd_buttons_update();
  1369. soft_pwm_core();
  1370. #ifdef BABYSTEPPING
  1371. applyBabysteps();
  1372. #endif //BABYSTEPPING
  1373. // Check if a stack overflow happened
  1374. if (!SdFatUtil::test_stack_integrity()) stack_error();
  1375. #if (defined(FANCHECK) && defined(TACH_0) && (TACH_0 > -1))
  1376. readFanTach();
  1377. #endif //(defined(TACH_0))
  1378. }
  1379. // Timer2 (originaly timer0) is shared with millies
  1380. #ifdef SYSTEM_TIMER_2
  1381. ISR(TIMER2_COMPB_vect)
  1382. #else //SYSTEM_TIMER_2
  1383. ISR(TIMER0_COMPB_vect)
  1384. #endif //SYSTEM_TIMER_2
  1385. {
  1386. DISABLE_SOFT_PWM_INTERRUPT();
  1387. sei();
  1388. soft_pwm_isr();
  1389. cli();
  1390. ENABLE_SOFT_PWM_INTERRUPT();
  1391. }
  1392. void check_max_temp_raw()
  1393. {
  1394. //heater
  1395. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1396. if (current_temperature_raw[0] <= maxttemp_raw[0]) {
  1397. #else
  1398. if (current_temperature_raw[0] >= maxttemp_raw[0]) {
  1399. #endif
  1400. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::max);
  1401. }
  1402. //bed
  1403. #if defined(BED_MAXTEMP) && (TEMP_SENSOR_BED != 0)
  1404. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1405. if (current_temperature_bed_raw <= bed_maxttemp_raw) {
  1406. #else
  1407. if (current_temperature_bed_raw >= bed_maxttemp_raw) {
  1408. #endif
  1409. set_temp_error(TempErrorSource::bed, 0, TempErrorType::max);
  1410. }
  1411. #endif
  1412. //ambient
  1413. #if defined(AMBIENT_MAXTEMP) && (TEMP_SENSOR_AMBIENT != 0)
  1414. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1415. if (current_temperature_raw_ambient <= ambient_maxttemp_raw) {
  1416. #else
  1417. if (current_temperature_raw_ambient >= ambient_maxttemp_raw) {
  1418. #endif
  1419. set_temp_error(TempErrorSource::ambient, 0, TempErrorType::max);
  1420. }
  1421. #endif
  1422. }
  1423. //! number of repeating the same state with consecutive step() calls
  1424. //! used to slow down text switching
  1425. struct alert_automaton_mintemp {
  1426. const char *m2;
  1427. alert_automaton_mintemp(const char *m2):m2(m2){}
  1428. private:
  1429. enum { ALERT_AUTOMATON_SPEED_DIV = 5 };
  1430. enum class States : uint8_t { Init = 0, TempAboveMintemp, ShowPleaseRestart, ShowMintemp };
  1431. States state = States::Init;
  1432. uint8_t repeat = ALERT_AUTOMATON_SPEED_DIV;
  1433. void substep(States next_state){
  1434. if( repeat == 0 ){
  1435. state = next_state; // advance to the next state
  1436. repeat = ALERT_AUTOMATON_SPEED_DIV; // and prepare repeating for it too
  1437. } else {
  1438. --repeat;
  1439. }
  1440. }
  1441. public:
  1442. //! brief state automaton step routine
  1443. //! @param current_temp current hotend/bed temperature (for computing simple hysteresis)
  1444. //! @param mintemp minimal temperature including hysteresis to check current_temp against
  1445. void step(float current_temp, float mintemp){
  1446. static const char m1[] PROGMEM = "Please restart";
  1447. switch(state){
  1448. case States::Init: // initial state - check hysteresis
  1449. if( current_temp > mintemp ){
  1450. state = States::TempAboveMintemp;
  1451. }
  1452. // otherwise keep the Err MINTEMP alert message on the display,
  1453. // i.e. do not transfer to state 1
  1454. break;
  1455. case States::TempAboveMintemp: // the temperature has risen above the hysteresis check
  1456. lcd_setalertstatuspgm(m2, LCD_STATUS_CRITICAL);
  1457. substep(States::ShowMintemp);
  1458. last_alert_sent_to_lcd = LCDALERT_MINTEMPFIXED;
  1459. break;
  1460. case States::ShowPleaseRestart: // displaying "Please restart"
  1461. lcd_setalertstatuspgm(m1, LCD_STATUS_CRITICAL);
  1462. substep(States::ShowMintemp);
  1463. last_alert_sent_to_lcd = LCDALERT_PLEASERESTART;
  1464. break;
  1465. case States::ShowMintemp: // displaying "MINTEMP fixed"
  1466. lcd_setalertstatuspgm(m2, LCD_STATUS_CRITICAL);
  1467. substep(States::ShowPleaseRestart);
  1468. last_alert_sent_to_lcd = LCDALERT_MINTEMPFIXED;
  1469. break;
  1470. }
  1471. }
  1472. };
  1473. static const char m2hotend[] PROGMEM = "MINTEMP HOTEND fixed";
  1474. static const char m2bed[] PROGMEM = "MINTEMP BED fixed";
  1475. static alert_automaton_mintemp alert_automaton_hotend(m2hotend), alert_automaton_bed(m2bed);
  1476. void check_min_temp_heater0()
  1477. {
  1478. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1479. if (current_temperature_raw[0] >= minttemp_raw[0]) {
  1480. #else
  1481. if (current_temperature_raw[0] <= minttemp_raw[0]) {
  1482. #endif
  1483. set_temp_error(TempErrorSource::hotend, 0, TempErrorType::min);
  1484. }
  1485. }
  1486. void check_min_temp_bed()
  1487. {
  1488. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1489. if (current_temperature_bed_raw >= bed_minttemp_raw) {
  1490. #else
  1491. if (current_temperature_bed_raw <= bed_minttemp_raw) {
  1492. #endif
  1493. set_temp_error(TempErrorSource::bed, 0, TempErrorType::min);
  1494. }
  1495. }
  1496. #ifdef AMBIENT_MINTEMP
  1497. void check_min_temp_ambient()
  1498. {
  1499. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1500. if (current_temperature_raw_ambient >= ambient_minttemp_raw) {
  1501. #else
  1502. if (current_temperature_raw_ambient <= ambient_minttemp_raw) {
  1503. #endif
  1504. set_temp_error(TempErrorSource::ambient, 0, TempErrorType::min);
  1505. }
  1506. }
  1507. #endif
  1508. void handle_temp_error()
  1509. {
  1510. // relay to the original handler
  1511. switch((TempErrorType)temp_error_state.type) {
  1512. case TempErrorType::min:
  1513. switch((TempErrorSource)temp_error_state.source) {
  1514. case TempErrorSource::hotend:
  1515. if(temp_error_state.assert) {
  1516. menu_set_serious_error(SERIOUS_ERR_MINTEMP_HEATER);
  1517. min_temp_error(temp_error_state.index);
  1518. } else {
  1519. // no recovery, just force the user to restart the printer
  1520. // which is a safer variant than just continuing printing
  1521. // The automaton also checks for hysteresis - the temperature must have reached a few degrees above the MINTEMP, before
  1522. // we shall signalize, that MINTEMP has been fixed
  1523. // Code notice: normally the alert_automaton instance would have been placed here
  1524. // as static alert_automaton_mintemp alert_automaton_hotend, but
  1525. alert_automaton_hotend.step(current_temperature[0], minttemp[0] + TEMP_HYSTERESIS);
  1526. }
  1527. break;
  1528. case TempErrorSource::bed:
  1529. if(temp_error_state.assert) {
  1530. menu_set_serious_error(SERIOUS_ERR_MINTEMP_BED);
  1531. bed_min_temp_error();
  1532. } else {
  1533. // no recovery, just force the user to restart the printer
  1534. // which is a safer variant than just continuing printing
  1535. alert_automaton_bed.step(current_temperature_bed, BED_MINTEMP + TEMP_HYSTERESIS);
  1536. }
  1537. break;
  1538. #ifdef AMBIENT_THERMISTOR
  1539. case TempErrorSource::ambient:
  1540. ambient_min_temp_error();
  1541. break;
  1542. #endif
  1543. }
  1544. break;
  1545. case TempErrorType::max:
  1546. switch((TempErrorSource)temp_error_state.source) {
  1547. case TempErrorSource::hotend:
  1548. max_temp_error(temp_error_state.index);
  1549. break;
  1550. case TempErrorSource::bed:
  1551. bed_max_temp_error();
  1552. break;
  1553. #ifdef AMBIENT_THERMISTOR
  1554. case TempErrorSource::ambient:
  1555. ambient_max_temp_error();
  1556. break;
  1557. #endif
  1558. }
  1559. break;
  1560. case TempErrorType::preheat:
  1561. case TempErrorType::runaway:
  1562. switch((TempErrorSource)temp_error_state.source) {
  1563. case TempErrorSource::hotend:
  1564. case TempErrorSource::bed:
  1565. temp_runaway_stop(
  1566. ((TempErrorType)temp_error_state.type == TempErrorType::preheat),
  1567. ((TempErrorSource)temp_error_state.source == TempErrorSource::bed));
  1568. break;
  1569. #ifdef AMBIENT_THERMISTOR
  1570. case TempErrorSource::ambient:
  1571. // not needed
  1572. break;
  1573. #endif
  1574. }
  1575. break;
  1576. #ifdef TEMP_MODEL
  1577. case TempErrorType::model:
  1578. if(temp_error_state.assert) {
  1579. if(IsStopped() == false) {
  1580. lcd_setalertstatuspgm(MSG_PAUSED_THERMAL_ERROR, LCD_STATUS_CRITICAL);
  1581. SERIAL_ECHOLNPGM("TM: error triggered!");
  1582. }
  1583. ThermalStop(true);
  1584. WRITE(BEEPER, HIGH);
  1585. } else {
  1586. temp_error_state.v = 0;
  1587. WRITE(BEEPER, LOW);
  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 timer5
  1662. CRITICAL_SECTION_START;
  1663. // CTC
  1664. TCCR5B &= ~(1<<WGM53);
  1665. TCCR5B |= (1<<WGM52);
  1666. TCCR5A &= ~(1<<WGM51);
  1667. TCCR5A &= ~(1<<WGM50);
  1668. // output mode = 00 (disconnected)
  1669. TCCR5A &= ~(3<<COM5A0);
  1670. TCCR5A &= ~(3<<COM5B0);
  1671. // x/256 prescaler
  1672. TCCR5B |= (1<<CS52);
  1673. TCCR5B &= ~(1<<CS51);
  1674. TCCR5B &= ~(1<<CS50);
  1675. // reset counter
  1676. TCNT5 = 0;
  1677. OCR5A = TIMER5_OCRA_OVF;
  1678. // clear pending interrupts, enable COMPA
  1679. TEMP_MGR_INT_FLAG_CLEAR();
  1680. ENABLE_TEMP_MGR_INTERRUPT();
  1681. CRITICAL_SECTION_END;
  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(TIMER5_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. sei();
  1975. temp_mgr_isr();
  1976. cli();
  1977. ENABLE_TEMP_MGR_INTERRUPT();
  1978. }
  1979. void disable_heater()
  1980. {
  1981. setAllTargetHotends(0);
  1982. setTargetBed(0);
  1983. CRITICAL_SECTION_START;
  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. CRITICAL_SECTION_END;
  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(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 - (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. void waiting_handler()
  2316. {
  2317. manage_heater();
  2318. host_keepalive();
  2319. host_autoreport();
  2320. checkFans();
  2321. lcd_update(0);
  2322. }
  2323. void wait(unsigned ms)
  2324. {
  2325. unsigned long mark = _millis() + ms;
  2326. while(_millis() < mark) {
  2327. if(temp_error_state.v) break;
  2328. waiting_handler();
  2329. }
  2330. }
  2331. void wait_temp()
  2332. {
  2333. while(current_temperature[0] < (target_temperature[0] - TEMP_HYSTERESIS)) {
  2334. if(temp_error_state.v) break;
  2335. waiting_handler();
  2336. }
  2337. }
  2338. void cooldown(float temp)
  2339. {
  2340. float old_speed = fanSpeedSoftPwm;
  2341. fanSpeedSoftPwm = 255;
  2342. while(current_temperature[0] >= temp) {
  2343. if(temp_error_state.v) break;
  2344. float ambient = current_temperature_ambient + temp_model::data.Ta_corr;
  2345. if(current_temperature[0] < (ambient + TEMP_HYSTERESIS)) {
  2346. // do not get stuck waiting very close to ambient temperature
  2347. break;
  2348. }
  2349. waiting_handler();
  2350. }
  2351. fanSpeedSoftPwm = old_speed;
  2352. }
  2353. uint16_t record(uint16_t samples = REC_BUFFER_SIZE) {
  2354. TempMgrGuard temp_mgr_guard;
  2355. uint16_t pos = 0;
  2356. while(pos < samples) {
  2357. if(!TEMP_MGR_INT_FLAG_STATE()) {
  2358. // temperatures not ready yet, just manage heaters while waiting to reduce jitter
  2359. manage_heater();
  2360. continue;
  2361. }
  2362. TEMP_MGR_INT_FLAG_CLEAR();
  2363. // manually repeat what the regular isr would do
  2364. if(adc_values_ready != true) continue;
  2365. adc_values_ready = false;
  2366. adc_start_cycle();
  2367. temp_mgr_isr();
  2368. // stop recording for an hard error condition
  2369. if(temp_error_state.v)
  2370. return 0;
  2371. // record a new entry
  2372. rec_entry& entry = rec_buffer[pos];
  2373. entry.temp = current_temperature_isr[0];
  2374. entry.pwm = soft_pwm[0];
  2375. ++pos;
  2376. // it's now safer to give regular serial/lcd updates a shot
  2377. waiting_handler();
  2378. }
  2379. return pos;
  2380. }
  2381. float cost_fn(uint16_t samples, float* const var, float v, uint8_t fan_pwm, float ambient)
  2382. {
  2383. *var = v;
  2384. temp_model::data.reset(rec_buffer[0].pwm, fan_pwm, rec_buffer[0].temp, ambient);
  2385. float err = 0;
  2386. for(uint16_t i = 1; i < samples; ++i) {
  2387. temp_model::data.step(rec_buffer[i].pwm, fan_pwm, rec_buffer[i].temp, ambient);
  2388. err += fabsf(temp_model::data.dT_err_prev);
  2389. }
  2390. return (err / (samples - 1));
  2391. }
  2392. constexpr float GOLDEN_RATIO = 0.6180339887498949;
  2393. void update_section(float points[2], const float bounds[2])
  2394. {
  2395. float d = GOLDEN_RATIO * (bounds[1] - bounds[0]);
  2396. points[0] = bounds[0] + d;
  2397. points[1] = bounds[1] - d;
  2398. }
  2399. float estimate(uint16_t samples,
  2400. float* const var, float min, float max,
  2401. float thr, uint16_t max_itr,
  2402. uint8_t fan_pwm, float ambient)
  2403. {
  2404. float orig = *var;
  2405. float e = NAN;
  2406. float points[2];
  2407. float bounds[2] = {min, max};
  2408. update_section(points, bounds);
  2409. for(uint8_t it = 0; it != max_itr; ++it) {
  2410. float c1 = cost_fn(samples, var, points[0], fan_pwm, ambient);
  2411. float c2 = cost_fn(samples, var, points[1], fan_pwm, ambient);
  2412. bool dir = (c2 < c1);
  2413. bounds[dir] = points[!dir];
  2414. update_section(points, bounds);
  2415. float x = points[!dir];
  2416. e = (1-GOLDEN_RATIO) * fabsf((bounds[0]-bounds[1]) / x);
  2417. printf_P(PSTR("TM iter:%u v:%.2f e:%.3f\n"), it, x, e);
  2418. if(e < thr) {
  2419. if(x == min || x == max) {
  2420. // real value likely outside of the search boundaries
  2421. break;
  2422. }
  2423. *var = x;
  2424. return e;
  2425. }
  2426. }
  2427. SERIAL_ECHOLNPGM("TM estimation did not converge");
  2428. *var = orig;
  2429. return NAN;
  2430. }
  2431. bool autotune(int16_t cal_temp)
  2432. {
  2433. uint16_t samples;
  2434. float e;
  2435. // bootstrap C/R values without fan
  2436. fanSpeedSoftPwm = 0;
  2437. for(uint8_t i = 0; i != 2; ++i) {
  2438. const char* PROGMEM verb = (i == 0? PSTR("initial"): PSTR("refining"));
  2439. target_temperature[0] = 0;
  2440. if(current_temperature[0] >= TEMP_MODEL_CAL_Tl) {
  2441. printf_P(PSTR("TM: cooling down to %dC\n"), TEMP_MODEL_CAL_Tl);
  2442. cooldown(TEMP_MODEL_CAL_Tl);
  2443. wait(10000);
  2444. }
  2445. // we need a valid R value for the initial C guess
  2446. if(isnan(temp_model::data.R[0]))
  2447. temp_model::data.R[0] = TEMP_MODEL_Rh;
  2448. printf_P(PSTR("TM: %S C estimation\n"), verb);
  2449. target_temperature[0] = cal_temp;
  2450. samples = record();
  2451. if(temp_error_state.v || !samples)
  2452. return true;
  2453. e = estimate(samples, &temp_model::data.C,
  2454. TEMP_MODEL_Cl, TEMP_MODEL_Ch, TEMP_MODEL_C_thr, TEMP_MODEL_C_itr,
  2455. 0, current_temperature_ambient);
  2456. if(isnan(e))
  2457. return true;
  2458. wait_temp();
  2459. if(i) break; // we don't need to refine R
  2460. wait(30000); // settle PID regulation
  2461. printf_P(PSTR("TM: %S R estimation @ %dC\n"), verb, cal_temp);
  2462. samples = record();
  2463. if(temp_error_state.v || !samples)
  2464. return true;
  2465. e = estimate(samples, &temp_model::data.R[0],
  2466. TEMP_MODEL_Rl, TEMP_MODEL_Rh, TEMP_MODEL_R_thr, TEMP_MODEL_R_itr,
  2467. 0, current_temperature_ambient);
  2468. if(isnan(e))
  2469. return true;
  2470. }
  2471. // Estimate fan losses at regular intervals, starting from full speed to avoid low-speed
  2472. // kickstart issues, although this requires us to wait more for the PID stabilization.
  2473. // Normally exhibits logarithmic behavior with the stock fan+shroud, so the shorter interval
  2474. // at lower speeds is helpful to increase the resolution of the interpolation.
  2475. fanSpeedSoftPwm = 255;
  2476. wait(30000);
  2477. for(int8_t i = TEMP_MODEL_R_SIZE - 1; i > 0; i -= TEMP_MODEL_CAL_R_STEP) {
  2478. fanSpeedSoftPwm = 256 / TEMP_MODEL_R_SIZE * (i + 1) - 1;
  2479. wait(10000);
  2480. printf_P(PSTR("TM: R[%u] estimation\n"), (unsigned)i);
  2481. samples = record();
  2482. if(temp_error_state.v || !samples)
  2483. return true;
  2484. // a fixed fan pwm (the norminal value) is used here, as soft_pwm_fan will be modified
  2485. // during fan measurements and we'd like to include that skew during normal operation.
  2486. e = estimate(samples, &temp_model::data.R[i],
  2487. TEMP_MODEL_Rl, temp_model::data.R[0], TEMP_MODEL_R_thr, TEMP_MODEL_R_itr,
  2488. i, current_temperature_ambient);
  2489. if(isnan(e))
  2490. return true;
  2491. }
  2492. // interpolate remaining steps to speed-up calibration
  2493. // TODO: verify that the sampled values are monotically increasing?
  2494. int8_t next = TEMP_MODEL_R_SIZE - 1;
  2495. for(uint8_t i = TEMP_MODEL_R_SIZE - 2; i != 0; --i) {
  2496. if(!((TEMP_MODEL_R_SIZE - i - 1) % TEMP_MODEL_CAL_R_STEP)) {
  2497. next = i;
  2498. continue;
  2499. }
  2500. int8_t prev = next - TEMP_MODEL_CAL_R_STEP;
  2501. if(prev < 0) prev = 0;
  2502. float f = (float)(i - prev) / TEMP_MODEL_CAL_R_STEP;
  2503. float d = (temp_model::data.R[next] - temp_model::data.R[prev]);
  2504. temp_model::data.R[i] = temp_model::data.R[prev] + d * f;
  2505. }
  2506. return false;
  2507. }
  2508. } // namespace temp_model_cal
  2509. void temp_model_autotune(int16_t temp)
  2510. {
  2511. if(moves_planned() || printer_active()) {
  2512. SERIAL_ECHOLNPGM("TM: printer needs to be idle for calibration");
  2513. return;
  2514. }
  2515. KEEPALIVE_STATE(IN_PROCESS);
  2516. // disable the model checking during self-calibration
  2517. bool was_enabled = temp_model::enabled;
  2518. temp_model_set_enabled(false);
  2519. SERIAL_ECHOLNPGM("TM: autotune start");
  2520. bool err = temp_model_cal::autotune(temp > 0 ? temp : TEMP_MODEL_CAL_Th);
  2521. // always reset temperature
  2522. target_temperature[0] = 0;
  2523. if(err) {
  2524. SERIAL_ECHOLNPGM("TM: autotune failed");
  2525. if(temp_error_state.v)
  2526. fanSpeedSoftPwm = 255;
  2527. } else {
  2528. fanSpeedSoftPwm = 0;
  2529. temp_model_set_enabled(was_enabled);
  2530. temp_model_report_settings();
  2531. }
  2532. }
  2533. #ifdef TEMP_MODEL_DEBUG
  2534. void temp_model_log_enable(bool enable)
  2535. {
  2536. if(enable) {
  2537. TempMgrGuard temp_mgr_guard;
  2538. temp_model::log_buf.entry.stamp = _millis();
  2539. }
  2540. temp_model::log_buf.enabled = enable;
  2541. }
  2542. #endif
  2543. #endif