temperature.cpp 84 KB

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