temperature.cpp 86 KB

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