My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

temperature.cpp 69KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * temperature.cpp - temperature control
  24. */
  25. #include "Marlin.h"
  26. #include "temperature.h"
  27. #include "thermistortables.h"
  28. #include "ultralcd.h"
  29. #include "planner.h"
  30. #include "language.h"
  31. #if ENABLED(HEATER_0_USES_MAX6675)
  32. #include "MarlinSPI.h"
  33. #endif
  34. #if ENABLED(BABYSTEPPING)
  35. #include "stepper.h"
  36. #endif
  37. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  38. #include "endstops.h"
  39. #endif
  40. #if ENABLED(USE_WATCHDOG)
  41. #include "watchdog.h"
  42. #endif
  43. #ifdef K1 // Defined in Configuration.h in the PID settings
  44. #define K2 (1.0-K1)
  45. #endif
  46. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  47. static void* heater_ttbl_map[2] = { (void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE };
  48. static uint8_t heater_ttbllen_map[2] = { HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN };
  49. #else
  50. static void* heater_ttbl_map[HOTENDS] = ARRAY_BY_HOTENDS((void*)HEATER_0_TEMPTABLE, (void*)HEATER_1_TEMPTABLE, (void*)HEATER_2_TEMPTABLE, (void*)HEATER_3_TEMPTABLE, (void*)HEATER_4_TEMPTABLE);
  51. static uint8_t heater_ttbllen_map[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN, HEATER_3_TEMPTABLE_LEN, HEATER_4_TEMPTABLE_LEN);
  52. #endif
  53. Temperature thermalManager;
  54. // public:
  55. float Temperature::current_temperature[HOTENDS] = { 0.0 },
  56. Temperature::current_temperature_bed = 0.0;
  57. int16_t Temperature::current_temperature_raw[HOTENDS] = { 0 },
  58. Temperature::target_temperature[HOTENDS] = { 0 },
  59. Temperature::current_temperature_bed_raw = 0;
  60. #if HAS_HEATER_BED
  61. int16_t Temperature::target_temperature_bed = 0;
  62. #endif
  63. // Initialized by settings.load()
  64. #if ENABLED(PIDTEMP)
  65. #if ENABLED(PID_PARAMS_PER_HOTEND) && HOTENDS > 1
  66. float Temperature::Kp[HOTENDS], Temperature::Ki[HOTENDS], Temperature::Kd[HOTENDS];
  67. #if ENABLED(PID_EXTRUSION_SCALING)
  68. float Temperature::Kc[HOTENDS];
  69. #endif
  70. #else
  71. float Temperature::Kp, Temperature::Ki, Temperature::Kd;
  72. #if ENABLED(PID_EXTRUSION_SCALING)
  73. float Temperature::Kc;
  74. #endif
  75. #endif
  76. #endif
  77. // Initialized by settings.load()
  78. #if ENABLED(PIDTEMPBED)
  79. float Temperature::bedKp, Temperature::bedKi, Temperature::bedKd;
  80. #endif
  81. #if ENABLED(BABYSTEPPING)
  82. volatile int Temperature::babystepsTodo[XYZ] = { 0 };
  83. #endif
  84. #if WATCH_HOTENDS
  85. uint16_t Temperature::watch_target_temp[HOTENDS] = { 0 };
  86. millis_t Temperature::watch_heater_next_ms[HOTENDS] = { 0 };
  87. #endif
  88. #if WATCH_THE_BED
  89. uint16_t Temperature::watch_target_bed_temp = 0;
  90. millis_t Temperature::watch_bed_next_ms = 0;
  91. #endif
  92. #if ENABLED(PREVENT_COLD_EXTRUSION)
  93. bool Temperature::allow_cold_extrude = false;
  94. int16_t Temperature::extrude_min_temp = EXTRUDE_MINTEMP;
  95. #endif
  96. // private:
  97. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  98. uint16_t Temperature::redundant_temperature_raw = 0;
  99. float Temperature::redundant_temperature = 0.0;
  100. #endif
  101. volatile bool Temperature::temp_meas_ready = false;
  102. #if ENABLED(PIDTEMP)
  103. float Temperature::temp_iState[HOTENDS] = { 0 },
  104. Temperature::temp_dState[HOTENDS] = { 0 },
  105. Temperature::pTerm[HOTENDS],
  106. Temperature::iTerm[HOTENDS],
  107. Temperature::dTerm[HOTENDS];
  108. #if ENABLED(PID_EXTRUSION_SCALING)
  109. float Temperature::cTerm[HOTENDS];
  110. long Temperature::last_e_position;
  111. long Temperature::lpq[LPQ_MAX_LEN];
  112. int Temperature::lpq_ptr = 0;
  113. #endif
  114. float Temperature::pid_error[HOTENDS];
  115. bool Temperature::pid_reset[HOTENDS];
  116. #endif
  117. #if ENABLED(PIDTEMPBED)
  118. float Temperature::temp_iState_bed = { 0 },
  119. Temperature::temp_dState_bed = { 0 },
  120. Temperature::pTerm_bed,
  121. Temperature::iTerm_bed,
  122. Temperature::dTerm_bed,
  123. Temperature::pid_error_bed;
  124. #else
  125. millis_t Temperature::next_bed_check_ms;
  126. #endif
  127. uint16_t Temperature::raw_temp_value[MAX_EXTRUDERS] = { 0 },
  128. Temperature::raw_temp_bed_value = 0;
  129. // Init min and max temp with extreme values to prevent false errors during startup
  130. int16_t Temperature::minttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP, HEATER_3_RAW_LO_TEMP, HEATER_4_RAW_LO_TEMP),
  131. Temperature::maxttemp_raw[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP, HEATER_3_RAW_HI_TEMP, HEATER_4_RAW_HI_TEMP),
  132. Temperature::minttemp[HOTENDS] = { 0 },
  133. Temperature::maxttemp[HOTENDS] = ARRAY_BY_HOTENDS1(16383);
  134. #ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
  135. uint8_t Temperature::consecutive_low_temperature_error[HOTENDS] = { 0 };
  136. #endif
  137. #ifdef MILLISECONDS_PREHEAT_TIME
  138. millis_t Temperature::preheat_end_time[HOTENDS] = { 0 };
  139. #endif
  140. #ifdef BED_MINTEMP
  141. int16_t Temperature::bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
  142. #endif
  143. #ifdef BED_MAXTEMP
  144. int16_t Temperature::bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
  145. #endif
  146. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  147. int8_t Temperature::meas_shift_index; // Index of a delayed sample in buffer
  148. #endif
  149. #if HAS_AUTO_FAN
  150. millis_t Temperature::next_auto_fan_check_ms = 0;
  151. #endif
  152. uint8_t Temperature::soft_pwm_amount[HOTENDS],
  153. Temperature::soft_pwm_amount_bed;
  154. #if ENABLED(FAN_SOFT_PWM)
  155. uint8_t Temperature::soft_pwm_amount_fan[FAN_COUNT],
  156. Temperature::soft_pwm_count_fan[FAN_COUNT];
  157. #endif
  158. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  159. uint16_t Temperature::current_raw_filwidth = 0; // Measured filament diameter - one extruder only
  160. #endif
  161. #if ENABLED(PROBING_HEATERS_OFF)
  162. bool Temperature::paused;
  163. #endif
  164. #if HEATER_IDLE_HANDLER
  165. millis_t Temperature::heater_idle_timeout_ms[HOTENDS] = { 0 };
  166. bool Temperature::heater_idle_timeout_exceeded[HOTENDS] = { false };
  167. #if HAS_TEMP_BED
  168. millis_t Temperature::bed_idle_timeout_ms = 0;
  169. bool Temperature::bed_idle_timeout_exceeded = false;
  170. #endif
  171. #endif
  172. #if ENABLED(ADC_KEYPAD)
  173. uint32_t Temperature::current_ADCKey_raw = 0;
  174. uint8_t Temperature::ADCKey_count = 0;
  175. #endif
  176. #if HAS_PID_HEATING
  177. /**
  178. * PID Autotuning (M303)
  179. *
  180. * Alternately heat and cool the nozzle, observing its behavior to
  181. * determine the best PID values to achieve a stable temperature.
  182. */
  183. void Temperature::PID_autotune(const float temp, const int8_t hotend, const int8_t ncycles, const bool set_result/*=false*/) {
  184. float input = 0.0;
  185. int cycles = 0;
  186. bool heating = true;
  187. millis_t next_temp_ms = millis(), t1 = next_temp_ms, t2 = next_temp_ms;
  188. long t_high = 0, t_low = 0;
  189. long bias, d;
  190. float Ku, Tu,
  191. workKp = 0, workKi = 0, workKd = 0,
  192. max = 0, min = 10000;
  193. #if WATCH_THE_BED || WATCH_HOTENDS
  194. const float watch_temp_target = temp -
  195. #if ENABLED(THERMAL_PROTECTION_BED) && ENABLED(PIDTEMPBED) && ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(PIDTEMP)
  196. (hotend < 0 ? (WATCH_BED_TEMP_INCREASE + TEMP_BED_HYSTERESIS + 1) : (WATCH_TEMP_INCREASE + TEMP_HYSTERESIS + 1))
  197. #elif ENABLED(THERMAL_PROTECTION_BED) && ENABLED(PIDTEMPBED)
  198. (WATCH_BED_TEMP_INCREASE + TEMP_BED_HYSTERESIS + 1)
  199. #else
  200. (WATCH_TEMP_INCREASE + TEMP_HYSTERESIS + 1)
  201. #endif
  202. ;
  203. const int8_t watch_temp_period =
  204. #if ENABLED(THERMAL_PROTECTION_BED) && ENABLED(PIDTEMPBED) && ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(PIDTEMP)
  205. hotend < 0 ? WATCH_BED_TEMP_PERIOD : WATCH_TEMP_PERIOD
  206. #elif ENABLED(THERMAL_PROTECTION_BED) && ENABLED(PIDTEMPBED)
  207. WATCH_BED_TEMP_PERIOD
  208. #else
  209. WATCH_TEMP_PERIOD
  210. #endif
  211. ;
  212. const int8_t watch_temp_increase =
  213. #if ENABLED(THERMAL_PROTECTION_BED) && ENABLED(PIDTEMPBED) && ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(PIDTEMP)
  214. hotend < 0 ? WATCH_BED_TEMP_INCREASE : WATCH_TEMP_INCREASE
  215. #elif ENABLED(THERMAL_PROTECTION_BED) && ENABLED(PIDTEMPBED)
  216. WATCH_BED_TEMP_INCREASE
  217. #else
  218. WATCH_TEMP_INCREASE
  219. #endif
  220. ;
  221. millis_t temp_change_ms = next_temp_ms + watch_temp_period * 1000UL;
  222. float next_watch_temp = 0.0;
  223. bool heated = false;
  224. #endif
  225. #if HAS_AUTO_FAN
  226. next_auto_fan_check_ms = next_temp_ms + 2500UL;
  227. #endif
  228. #if ENABLED(PIDTEMP)
  229. #define _TOP_HOTEND HOTENDS - 1
  230. #else
  231. #define _TOP_HOTEND -1
  232. #endif
  233. #if ENABLED(PIDTEMPBED)
  234. #define _BOT_HOTEND -1
  235. #else
  236. #define _BOT_HOTEND 0
  237. #endif
  238. if (!WITHIN(hotend, _BOT_HOTEND, _TOP_HOTEND)) {
  239. SERIAL_ECHOLN(MSG_PID_BAD_EXTRUDER_NUM);
  240. return;
  241. }
  242. SERIAL_ECHOLN(MSG_PID_AUTOTUNE_START);
  243. disable_all_heaters(); // switch off all heaters.
  244. #if HAS_PID_FOR_BOTH
  245. if (hotend < 0)
  246. soft_pwm_amount_bed = bias = d = (MAX_BED_POWER) >> 1;
  247. else
  248. soft_pwm_amount[hotend] = bias = d = (PID_MAX) >> 1;
  249. #elif ENABLED(PIDTEMP)
  250. soft_pwm_amount[hotend] = bias = d = (PID_MAX) >> 1;
  251. #else
  252. soft_pwm_amount_bed = bias = d = (MAX_BED_POWER) >> 1;
  253. #endif
  254. wait_for_heatup = true;
  255. // PID Tuning loop
  256. while (wait_for_heatup) {
  257. const millis_t ms = millis();
  258. if (temp_meas_ready) { // temp sample ready
  259. updateTemperaturesFromRawValues();
  260. input =
  261. #if HAS_PID_FOR_BOTH
  262. hotend < 0 ? current_temperature_bed : current_temperature[hotend]
  263. #elif ENABLED(PIDTEMP)
  264. current_temperature[hotend]
  265. #else
  266. current_temperature_bed
  267. #endif
  268. ;
  269. NOLESS(max, input);
  270. NOMORE(min, input);
  271. #if HAS_AUTO_FAN
  272. if (ELAPSED(ms, next_auto_fan_check_ms)) {
  273. checkExtruderAutoFans();
  274. next_auto_fan_check_ms = ms + 2500UL;
  275. }
  276. #endif
  277. if (heating && input > temp) {
  278. if (ELAPSED(ms, t2 + 5000UL)) {
  279. heating = false;
  280. #if HAS_PID_FOR_BOTH
  281. if (hotend < 0)
  282. soft_pwm_amount_bed = (bias - d) >> 1;
  283. else
  284. soft_pwm_amount[hotend] = (bias - d) >> 1;
  285. #elif ENABLED(PIDTEMP)
  286. soft_pwm_amount[hotend] = (bias - d) >> 1;
  287. #elif ENABLED(PIDTEMPBED)
  288. soft_pwm_amount_bed = (bias - d) >> 1;
  289. #endif
  290. t1 = ms;
  291. t_high = t1 - t2;
  292. max = temp;
  293. }
  294. }
  295. if (!heating && input < temp) {
  296. if (ELAPSED(ms, t1 + 5000UL)) {
  297. heating = true;
  298. t2 = ms;
  299. t_low = t2 - t1;
  300. if (cycles > 0) {
  301. long max_pow =
  302. #if HAS_PID_FOR_BOTH
  303. hotend < 0 ? MAX_BED_POWER : PID_MAX
  304. #elif ENABLED(PIDTEMP)
  305. PID_MAX
  306. #else
  307. MAX_BED_POWER
  308. #endif
  309. ;
  310. bias += (d * (t_high - t_low)) / (t_low + t_high);
  311. bias = constrain(bias, 20, max_pow - 20);
  312. d = (bias > max_pow >> 1) ? max_pow - 1 - bias : bias;
  313. SERIAL_PROTOCOLPAIR(MSG_BIAS, bias);
  314. SERIAL_PROTOCOLPAIR(MSG_D, d);
  315. SERIAL_PROTOCOLPAIR(MSG_T_MIN, min);
  316. SERIAL_PROTOCOLPAIR(MSG_T_MAX, max);
  317. if (cycles > 2) {
  318. Ku = (4.0 * d) / (M_PI * (max - min) * 0.5);
  319. Tu = ((float)(t_low + t_high) * 0.001);
  320. SERIAL_PROTOCOLPAIR(MSG_KU, Ku);
  321. SERIAL_PROTOCOLPAIR(MSG_TU, Tu);
  322. workKp = 0.6 * Ku;
  323. workKi = 2 * workKp / Tu;
  324. workKd = workKp * Tu * 0.125;
  325. SERIAL_PROTOCOLLNPGM("\n" MSG_CLASSIC_PID);
  326. SERIAL_PROTOCOLPAIR(MSG_KP, workKp);
  327. SERIAL_PROTOCOLPAIR(MSG_KI, workKi);
  328. SERIAL_PROTOCOLLNPAIR(MSG_KD, workKd);
  329. /**
  330. workKp = 0.33*Ku;
  331. workKi = workKp/Tu;
  332. workKd = workKp*Tu/3;
  333. SERIAL_PROTOCOLLNPGM(" Some overshoot");
  334. SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
  335. SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
  336. SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
  337. workKp = 0.2*Ku;
  338. workKi = 2*workKp/Tu;
  339. workKd = workKp*Tu/3;
  340. SERIAL_PROTOCOLLNPGM(" No overshoot");
  341. SERIAL_PROTOCOLPAIR(" Kp: ", workKp);
  342. SERIAL_PROTOCOLPAIR(" Ki: ", workKi);
  343. SERIAL_PROTOCOLPAIR(" Kd: ", workKd);
  344. */
  345. }
  346. }
  347. #if HAS_PID_FOR_BOTH
  348. if (hotend < 0)
  349. soft_pwm_amount_bed = (bias + d) >> 1;
  350. else
  351. soft_pwm_amount[hotend] = (bias + d) >> 1;
  352. #elif ENABLED(PIDTEMP)
  353. soft_pwm_amount[hotend] = (bias + d) >> 1;
  354. #else
  355. soft_pwm_amount_bed = (bias + d) >> 1;
  356. #endif
  357. cycles++;
  358. min = temp;
  359. }
  360. }
  361. }
  362. #define MAX_OVERSHOOT_PID_AUTOTUNE 20
  363. if (input > temp + MAX_OVERSHOOT_PID_AUTOTUNE) {
  364. SERIAL_PROTOCOLLNPGM(MSG_PID_TEMP_TOO_HIGH);
  365. break;
  366. }
  367. // Every 2 seconds...
  368. if (ELAPSED(ms, next_temp_ms)) {
  369. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  370. print_heaterstates();
  371. SERIAL_EOL();
  372. #endif
  373. next_temp_ms = ms + 2000UL;
  374. #if WATCH_THE_BED || WATCH_HOTENDS
  375. if (!heated && input > next_watch_temp) {
  376. if (input > watch_temp_target) heated = true;
  377. next_watch_temp = input + watch_temp_increase;
  378. temp_change_ms = ms + watch_temp_period * 1000UL;
  379. }
  380. else if (!heated && ELAPSED(ms, temp_change_ms))
  381. _temp_error(hotend, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
  382. else if (heated && input < temp - MAX_OVERSHOOT_PID_AUTOTUNE)
  383. _temp_error(hotend, PSTR(MSG_T_THERMAL_RUNAWAY), PSTR(MSG_THERMAL_RUNAWAY));
  384. #endif
  385. } // every 2 seconds
  386. // Timeout after 20 minutes since the last undershoot/overshoot cycle
  387. if (((ms - t1) + (ms - t2)) > (20L * 60L * 1000L)) {
  388. SERIAL_PROTOCOLLNPGM(MSG_PID_TIMEOUT);
  389. break;
  390. }
  391. if (cycles > ncycles) {
  392. SERIAL_PROTOCOLLNPGM(MSG_PID_AUTOTUNE_FINISHED);
  393. #if HAS_PID_FOR_BOTH
  394. const char* estring = hotend < 0 ? "bed" : "";
  395. SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kp ", workKp); SERIAL_EOL();
  396. SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Ki ", workKi); SERIAL_EOL();
  397. SERIAL_PROTOCOLPAIR("#define DEFAULT_", estring); SERIAL_PROTOCOLPAIR("Kd ", workKd); SERIAL_EOL();
  398. #elif ENABLED(PIDTEMP)
  399. SERIAL_PROTOCOLPAIR("#define DEFAULT_Kp ", workKp); SERIAL_EOL();
  400. SERIAL_PROTOCOLPAIR("#define DEFAULT_Ki ", workKi); SERIAL_EOL();
  401. SERIAL_PROTOCOLPAIR("#define DEFAULT_Kd ", workKd); SERIAL_EOL();
  402. #else
  403. SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKp ", workKp); SERIAL_EOL();
  404. SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKi ", workKi); SERIAL_EOL();
  405. SERIAL_PROTOCOLPAIR("#define DEFAULT_bedKd ", workKd); SERIAL_EOL();
  406. #endif
  407. #define _SET_BED_PID() do { \
  408. bedKp = workKp; \
  409. bedKi = scalePID_i(workKi); \
  410. bedKd = scalePID_d(workKd); \
  411. }while(0)
  412. #define _SET_EXTRUDER_PID() do { \
  413. PID_PARAM(Kp, hotend) = workKp; \
  414. PID_PARAM(Ki, hotend) = scalePID_i(workKi); \
  415. PID_PARAM(Kd, hotend) = scalePID_d(workKd); \
  416. updatePID(); }while(0)
  417. // Use the result? (As with "M303 U1")
  418. if (set_result) {
  419. #if HAS_PID_FOR_BOTH
  420. if (hotend < 0)
  421. _SET_BED_PID();
  422. else
  423. _SET_EXTRUDER_PID();
  424. #elif ENABLED(PIDTEMP)
  425. _SET_EXTRUDER_PID();
  426. #else
  427. _SET_BED_PID();
  428. #endif
  429. }
  430. return;
  431. }
  432. lcd_update();
  433. }
  434. disable_all_heaters();
  435. }
  436. #endif // HAS_PID_HEATING
  437. /**
  438. * Class and Instance Methods
  439. */
  440. Temperature::Temperature() { }
  441. int Temperature::getHeaterPower(int heater) {
  442. return heater < 0 ? soft_pwm_amount_bed : soft_pwm_amount[heater];
  443. }
  444. #if HAS_AUTO_FAN
  445. void Temperature::checkExtruderAutoFans() {
  446. static const int8_t fanPin[] PROGMEM = { E0_AUTO_FAN_PIN, E1_AUTO_FAN_PIN, E2_AUTO_FAN_PIN, E3_AUTO_FAN_PIN, E4_AUTO_FAN_PIN };
  447. static const uint8_t fanBit[] PROGMEM = {
  448. 0,
  449. AUTO_1_IS_0 ? 0 : 1,
  450. AUTO_2_IS_0 ? 0 : AUTO_2_IS_1 ? 1 : 2,
  451. AUTO_3_IS_0 ? 0 : AUTO_3_IS_1 ? 1 : AUTO_3_IS_2 ? 2 : 3,
  452. AUTO_4_IS_0 ? 0 : AUTO_4_IS_1 ? 1 : AUTO_4_IS_2 ? 2 : AUTO_4_IS_3 ? 3 : 4
  453. };
  454. uint8_t fanState = 0;
  455. HOTEND_LOOP()
  456. if (current_temperature[e] > EXTRUDER_AUTO_FAN_TEMPERATURE)
  457. SBI(fanState, pgm_read_byte(&fanBit[e]));
  458. uint8_t fanDone = 0;
  459. for (uint8_t f = 0; f < COUNT(fanPin); f++) {
  460. int8_t pin = pgm_read_byte(&fanPin[f]);
  461. const uint8_t bit = pgm_read_byte(&fanBit[f]);
  462. if (pin >= 0 && !TEST(fanDone, bit)) {
  463. uint8_t newFanSpeed = TEST(fanState, bit) ? EXTRUDER_AUTO_FAN_SPEED : 0;
  464. // this idiom allows both digital and PWM fan outputs (see M42 handling).
  465. digitalWrite(pin, newFanSpeed);
  466. analogWrite(pin, newFanSpeed);
  467. SBI(fanDone, bit);
  468. }
  469. }
  470. }
  471. #endif // HAS_AUTO_FAN
  472. //
  473. // Temperature Error Handlers
  474. //
  475. void Temperature::_temp_error(const int8_t e, const char * const serial_msg, const char * const lcd_msg) {
  476. static bool killed = false;
  477. if (IsRunning()) {
  478. SERIAL_ERROR_START();
  479. serialprintPGM(serial_msg);
  480. SERIAL_ERRORPGM(MSG_STOPPED_HEATER);
  481. if (e >= 0) SERIAL_ERRORLN((int)e); else SERIAL_ERRORLNPGM(MSG_HEATER_BED);
  482. }
  483. #if DISABLED(BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE)
  484. if (!killed) {
  485. Running = false;
  486. killed = true;
  487. kill(lcd_msg);
  488. }
  489. else
  490. disable_all_heaters(); // paranoia
  491. #endif
  492. }
  493. void Temperature::max_temp_error(const int8_t e) {
  494. #if HAS_TEMP_BED
  495. _temp_error(e, PSTR(MSG_T_MAXTEMP), e >= 0 ? PSTR(MSG_ERR_MAXTEMP) : PSTR(MSG_ERR_MAXTEMP_BED));
  496. #else
  497. _temp_error(HOTEND_INDEX, PSTR(MSG_T_MAXTEMP), PSTR(MSG_ERR_MAXTEMP));
  498. #if HOTENDS == 1
  499. UNUSED(e);
  500. #endif
  501. #endif
  502. }
  503. void Temperature::min_temp_error(const int8_t e) {
  504. #if HAS_TEMP_BED
  505. _temp_error(e, PSTR(MSG_T_MINTEMP), e >= 0 ? PSTR(MSG_ERR_MINTEMP) : PSTR(MSG_ERR_MINTEMP_BED));
  506. #else
  507. _temp_error(HOTEND_INDEX, PSTR(MSG_T_MINTEMP), PSTR(MSG_ERR_MINTEMP));
  508. #if HOTENDS == 1
  509. UNUSED(e);
  510. #endif
  511. #endif
  512. }
  513. float Temperature::get_pid_output(const int8_t e) {
  514. #if HOTENDS == 1
  515. UNUSED(e);
  516. #define _HOTEND_TEST true
  517. #else
  518. #define _HOTEND_TEST e == active_extruder
  519. #endif
  520. float pid_output;
  521. #if ENABLED(PIDTEMP)
  522. #if DISABLED(PID_OPENLOOP)
  523. pid_error[HOTEND_INDEX] = target_temperature[HOTEND_INDEX] - current_temperature[HOTEND_INDEX];
  524. dTerm[HOTEND_INDEX] = K2 * PID_PARAM(Kd, HOTEND_INDEX) * (current_temperature[HOTEND_INDEX] - temp_dState[HOTEND_INDEX]) + K1 * dTerm[HOTEND_INDEX];
  525. temp_dState[HOTEND_INDEX] = current_temperature[HOTEND_INDEX];
  526. #if HEATER_IDLE_HANDLER
  527. if (heater_idle_timeout_exceeded[HOTEND_INDEX]) {
  528. pid_output = 0;
  529. pid_reset[HOTEND_INDEX] = true;
  530. }
  531. else
  532. #endif
  533. if (pid_error[HOTEND_INDEX] > PID_FUNCTIONAL_RANGE) {
  534. pid_output = BANG_MAX;
  535. pid_reset[HOTEND_INDEX] = true;
  536. }
  537. else if (pid_error[HOTEND_INDEX] < -(PID_FUNCTIONAL_RANGE) || target_temperature[HOTEND_INDEX] == 0
  538. #if HEATER_IDLE_HANDLER
  539. || heater_idle_timeout_exceeded[HOTEND_INDEX]
  540. #endif
  541. ) {
  542. pid_output = 0;
  543. pid_reset[HOTEND_INDEX] = true;
  544. }
  545. else {
  546. if (pid_reset[HOTEND_INDEX]) {
  547. temp_iState[HOTEND_INDEX] = 0.0;
  548. pid_reset[HOTEND_INDEX] = false;
  549. }
  550. pTerm[HOTEND_INDEX] = PID_PARAM(Kp, HOTEND_INDEX) * pid_error[HOTEND_INDEX];
  551. temp_iState[HOTEND_INDEX] += pid_error[HOTEND_INDEX];
  552. iTerm[HOTEND_INDEX] = PID_PARAM(Ki, HOTEND_INDEX) * temp_iState[HOTEND_INDEX];
  553. pid_output = pTerm[HOTEND_INDEX] + iTerm[HOTEND_INDEX] - dTerm[HOTEND_INDEX];
  554. #if ENABLED(PID_EXTRUSION_SCALING)
  555. cTerm[HOTEND_INDEX] = 0;
  556. if (_HOTEND_TEST) {
  557. long e_position = stepper.position(E_AXIS);
  558. if (e_position > last_e_position) {
  559. lpq[lpq_ptr] = e_position - last_e_position;
  560. last_e_position = e_position;
  561. }
  562. else {
  563. lpq[lpq_ptr] = 0;
  564. }
  565. if (++lpq_ptr >= lpq_len) lpq_ptr = 0;
  566. cTerm[HOTEND_INDEX] = (lpq[lpq_ptr] * planner.steps_to_mm[E_AXIS]) * PID_PARAM(Kc, HOTEND_INDEX);
  567. pid_output += cTerm[HOTEND_INDEX];
  568. }
  569. #endif // PID_EXTRUSION_SCALING
  570. if (pid_output > PID_MAX) {
  571. if (pid_error[HOTEND_INDEX] > 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
  572. pid_output = PID_MAX;
  573. }
  574. else if (pid_output < 0) {
  575. if (pid_error[HOTEND_INDEX] < 0) temp_iState[HOTEND_INDEX] -= pid_error[HOTEND_INDEX]; // conditional un-integration
  576. pid_output = 0;
  577. }
  578. }
  579. #else
  580. pid_output = constrain(target_temperature[HOTEND_INDEX], 0, PID_MAX);
  581. #endif // PID_OPENLOOP
  582. #if ENABLED(PID_DEBUG)
  583. SERIAL_ECHO_START();
  584. SERIAL_ECHOPAIR(MSG_PID_DEBUG, HOTEND_INDEX);
  585. SERIAL_ECHOPAIR(MSG_PID_DEBUG_INPUT, current_temperature[HOTEND_INDEX]);
  586. SERIAL_ECHOPAIR(MSG_PID_DEBUG_OUTPUT, pid_output);
  587. SERIAL_ECHOPAIR(MSG_PID_DEBUG_PTERM, pTerm[HOTEND_INDEX]);
  588. SERIAL_ECHOPAIR(MSG_PID_DEBUG_ITERM, iTerm[HOTEND_INDEX]);
  589. SERIAL_ECHOPAIR(MSG_PID_DEBUG_DTERM, dTerm[HOTEND_INDEX]);
  590. #if ENABLED(PID_EXTRUSION_SCALING)
  591. SERIAL_ECHOPAIR(MSG_PID_DEBUG_CTERM, cTerm[HOTEND_INDEX]);
  592. #endif
  593. SERIAL_EOL();
  594. #endif // PID_DEBUG
  595. #else /* PID off */
  596. #if HEATER_IDLE_HANDLER
  597. if (heater_idle_timeout_exceeded[HOTEND_INDEX])
  598. pid_output = 0;
  599. else
  600. #endif
  601. pid_output = (current_temperature[HOTEND_INDEX] < target_temperature[HOTEND_INDEX]) ? PID_MAX : 0;
  602. #endif
  603. return pid_output;
  604. }
  605. #if ENABLED(PIDTEMPBED)
  606. float Temperature::get_pid_output_bed() {
  607. float pid_output;
  608. #if DISABLED(PID_OPENLOOP)
  609. pid_error_bed = target_temperature_bed - current_temperature_bed;
  610. pTerm_bed = bedKp * pid_error_bed;
  611. temp_iState_bed += pid_error_bed;
  612. iTerm_bed = bedKi * temp_iState_bed;
  613. dTerm_bed = K2 * bedKd * (current_temperature_bed - temp_dState_bed) + K1 * dTerm_bed;
  614. temp_dState_bed = current_temperature_bed;
  615. pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
  616. if (pid_output > MAX_BED_POWER) {
  617. if (pid_error_bed > 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
  618. pid_output = MAX_BED_POWER;
  619. }
  620. else if (pid_output < 0) {
  621. if (pid_error_bed < 0) temp_iState_bed -= pid_error_bed; // conditional un-integration
  622. pid_output = 0;
  623. }
  624. #else
  625. pid_output = constrain(target_temperature_bed, 0, MAX_BED_POWER);
  626. #endif // PID_OPENLOOP
  627. #if ENABLED(PID_BED_DEBUG)
  628. SERIAL_ECHO_START();
  629. SERIAL_ECHOPGM(" PID_BED_DEBUG ");
  630. SERIAL_ECHOPGM(": Input ");
  631. SERIAL_ECHO(current_temperature_bed);
  632. SERIAL_ECHOPGM(" Output ");
  633. SERIAL_ECHO(pid_output);
  634. SERIAL_ECHOPGM(" pTerm ");
  635. SERIAL_ECHO(pTerm_bed);
  636. SERIAL_ECHOPGM(" iTerm ");
  637. SERIAL_ECHO(iTerm_bed);
  638. SERIAL_ECHOPGM(" dTerm ");
  639. SERIAL_ECHOLN(dTerm_bed);
  640. #endif // PID_BED_DEBUG
  641. return pid_output;
  642. }
  643. #endif // PIDTEMPBED
  644. /**
  645. * Manage heating activities for extruder hot-ends and a heated bed
  646. * - Acquire updated temperature readings
  647. * - Also resets the watchdog timer
  648. * - Invoke thermal runaway protection
  649. * - Manage extruder auto-fan
  650. * - Apply filament width to the extrusion rate (may move)
  651. * - Update the heated bed PID output value
  652. */
  653. /**
  654. * The following line SOMETIMES results in the dreaded "unable to find a register to spill in class 'POINTER_REGS'"
  655. * compile error.
  656. * thermal_runaway_protection(&thermal_runaway_state_machine[e], &thermal_runaway_timer[e], current_temperature[e], target_temperature[e], e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS);
  657. *
  658. * This is due to a bug in the C++ compiler used by the Arduino IDE from 1.6.10 to at least 1.8.1.
  659. *
  660. * The work around is to add the compiler flag "__attribute__((__optimize__("O2")))" to the declaration for manage_heater()
  661. */
  662. //void Temperature::manage_heater() __attribute__((__optimize__("O2")));
  663. void Temperature::manage_heater() {
  664. if (!temp_meas_ready) return;
  665. updateTemperaturesFromRawValues(); // also resets the watchdog
  666. #if ENABLED(HEATER_0_USES_MAX6675)
  667. if (current_temperature[0] > min(HEATER_0_MAXTEMP, MAX6675_TMAX - 1.0)) max_temp_error(0);
  668. if (current_temperature[0] < max(HEATER_0_MINTEMP, MAX6675_TMIN + .01)) min_temp_error(0);
  669. #endif
  670. #if WATCH_HOTENDS || WATCH_THE_BED || DISABLED(PIDTEMPBED) || HAS_AUTO_FAN || HEATER_IDLE_HANDLER
  671. millis_t ms = millis();
  672. #endif
  673. HOTEND_LOOP() {
  674. #if HEATER_IDLE_HANDLER
  675. if (!heater_idle_timeout_exceeded[e] && heater_idle_timeout_ms[e] && ELAPSED(ms, heater_idle_timeout_ms[e]))
  676. heater_idle_timeout_exceeded[e] = true;
  677. #endif
  678. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  679. // Check for thermal runaway
  680. thermal_runaway_protection(&thermal_runaway_state_machine[e], &thermal_runaway_timer[e], current_temperature[e], target_temperature[e], e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS);
  681. #endif
  682. soft_pwm_amount[e] = (current_temperature[e] > minttemp[e] || is_preheating(e)) && current_temperature[e] < maxttemp[e] ? (int)get_pid_output(e) >> 1 : 0;
  683. #if WATCH_HOTENDS
  684. // Make sure temperature is increasing
  685. if (watch_heater_next_ms[e] && ELAPSED(ms, watch_heater_next_ms[e])) { // Time to check this extruder?
  686. if (degHotend(e) < watch_target_temp[e]) // Failed to increase enough?
  687. _temp_error(e, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
  688. else // Start again if the target is still far off
  689. start_watching_heater(e);
  690. }
  691. #endif
  692. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  693. // Make sure measured temperatures are close together
  694. if (FABS(current_temperature[0] - redundant_temperature) > MAX_REDUNDANT_TEMP_SENSOR_DIFF)
  695. _temp_error(0, PSTR(MSG_REDUNDANCY), PSTR(MSG_ERR_REDUNDANT_TEMP));
  696. #endif
  697. } // HOTEND_LOOP
  698. #if HAS_AUTO_FAN
  699. if (ELAPSED(ms, next_auto_fan_check_ms)) { // only need to check fan state very infrequently
  700. checkExtruderAutoFans();
  701. next_auto_fan_check_ms = ms + 2500UL;
  702. }
  703. #endif
  704. // Control the extruder rate based on the width sensor
  705. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  706. if (filament_sensor) {
  707. meas_shift_index = filwidth_delay_index[0] - meas_delay_cm;
  708. if (meas_shift_index < 0) meas_shift_index += MAX_MEASUREMENT_DELAY + 1; //loop around buffer if needed
  709. meas_shift_index = constrain(meas_shift_index, 0, MAX_MEASUREMENT_DELAY);
  710. // Get the delayed info and add 100 to reconstitute to a percent of
  711. // the nominal filament diameter then square it to get an area
  712. float vmroot = measurement_delay[meas_shift_index] * 0.01 + 1.0;
  713. NOLESS(vmroot, 0.1);
  714. planner.volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = 1.0 / CIRCLE_AREA(vmroot / 2);
  715. planner.refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  716. }
  717. #endif // FILAMENT_WIDTH_SENSOR
  718. #if WATCH_THE_BED
  719. // Make sure temperature is increasing
  720. if (watch_bed_next_ms && ELAPSED(ms, watch_bed_next_ms)) { // Time to check the bed?
  721. if (degBed() < watch_target_bed_temp) // Failed to increase enough?
  722. _temp_error(-1, PSTR(MSG_T_HEATING_FAILED), PSTR(MSG_HEATING_FAILED_LCD));
  723. else // Start again if the target is still far off
  724. start_watching_bed();
  725. }
  726. #endif // WATCH_THE_BED
  727. #if DISABLED(PIDTEMPBED)
  728. if (PENDING(ms, next_bed_check_ms)) return;
  729. next_bed_check_ms = ms + BED_CHECK_INTERVAL;
  730. #endif
  731. #if HAS_TEMP_BED
  732. #if HEATER_IDLE_HANDLER
  733. if (!bed_idle_timeout_exceeded && bed_idle_timeout_ms && ELAPSED(ms, bed_idle_timeout_ms))
  734. bed_idle_timeout_exceeded = true;
  735. #endif
  736. #if HAS_THERMALLY_PROTECTED_BED
  737. thermal_runaway_protection(&thermal_runaway_bed_state_machine, &thermal_runaway_bed_timer, current_temperature_bed, target_temperature_bed, -1, THERMAL_PROTECTION_BED_PERIOD, THERMAL_PROTECTION_BED_HYSTERESIS);
  738. #endif
  739. #if HEATER_IDLE_HANDLER
  740. if (bed_idle_timeout_exceeded)
  741. {
  742. soft_pwm_amount_bed = 0;
  743. #if DISABLED(PIDTEMPBED)
  744. WRITE_HEATER_BED(LOW);
  745. #endif
  746. }
  747. else
  748. #endif
  749. {
  750. #if ENABLED(PIDTEMPBED)
  751. soft_pwm_amount_bed = WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP) ? (int)get_pid_output_bed() >> 1 : 0;
  752. #elif ENABLED(BED_LIMIT_SWITCHING)
  753. // Check if temperature is within the correct band
  754. if (WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP)) {
  755. if (current_temperature_bed >= target_temperature_bed + BED_HYSTERESIS)
  756. soft_pwm_amount_bed = 0;
  757. else if (current_temperature_bed <= target_temperature_bed - (BED_HYSTERESIS))
  758. soft_pwm_amount_bed = MAX_BED_POWER >> 1;
  759. }
  760. else {
  761. soft_pwm_amount_bed = 0;
  762. WRITE_HEATER_BED(LOW);
  763. }
  764. #else // !PIDTEMPBED && !BED_LIMIT_SWITCHING
  765. // Check if temperature is within the correct range
  766. if (WITHIN(current_temperature_bed, BED_MINTEMP, BED_MAXTEMP)) {
  767. soft_pwm_amount_bed = current_temperature_bed < target_temperature_bed ? MAX_BED_POWER >> 1 : 0;
  768. }
  769. else {
  770. soft_pwm_amount_bed = 0;
  771. WRITE_HEATER_BED(LOW);
  772. }
  773. #endif
  774. }
  775. #endif // HAS_TEMP_BED
  776. }
  777. #define PGM_RD_W(x) (short)pgm_read_word(&x)
  778. // Derived from RepRap FiveD extruder::getTemperature()
  779. // For hot end temperature measurement.
  780. float Temperature::analog2temp(int raw, uint8_t e) {
  781. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  782. if (e > HOTENDS)
  783. #else
  784. if (e >= HOTENDS)
  785. #endif
  786. {
  787. SERIAL_ERROR_START();
  788. SERIAL_ERROR((int)e);
  789. SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER_NUM);
  790. kill(PSTR(MSG_KILLED));
  791. return 0.0;
  792. }
  793. #if ENABLED(HEATER_0_USES_MAX6675)
  794. if (e == 0) return 0.25 * raw;
  795. #endif
  796. if (heater_ttbl_map[e] != NULL) {
  797. float celsius = 0;
  798. uint8_t i;
  799. short(*tt)[][2] = (short(*)[][2])(heater_ttbl_map[e]);
  800. for (i = 1; i < heater_ttbllen_map[e]; i++) {
  801. if (PGM_RD_W((*tt)[i][0]) > raw) {
  802. celsius = PGM_RD_W((*tt)[i - 1][1]) +
  803. (raw - PGM_RD_W((*tt)[i - 1][0])) *
  804. (float)(PGM_RD_W((*tt)[i][1]) - PGM_RD_W((*tt)[i - 1][1])) /
  805. (float)(PGM_RD_W((*tt)[i][0]) - PGM_RD_W((*tt)[i - 1][0]));
  806. break;
  807. }
  808. }
  809. // Overflow: Set to last value in the table
  810. if (i == heater_ttbllen_map[e]) celsius = PGM_RD_W((*tt)[i - 1][1]);
  811. return celsius;
  812. }
  813. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
  814. }
  815. // Derived from RepRap FiveD extruder::getTemperature()
  816. // For bed temperature measurement.
  817. float Temperature::analog2tempBed(const int raw) {
  818. #if ENABLED(BED_USES_THERMISTOR)
  819. float celsius = 0;
  820. byte i;
  821. for (i = 1; i < BEDTEMPTABLE_LEN; i++) {
  822. if (PGM_RD_W(BEDTEMPTABLE[i][0]) > raw) {
  823. celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]) +
  824. (raw - PGM_RD_W(BEDTEMPTABLE[i - 1][0])) *
  825. (float)(PGM_RD_W(BEDTEMPTABLE[i][1]) - PGM_RD_W(BEDTEMPTABLE[i - 1][1])) /
  826. (float)(PGM_RD_W(BEDTEMPTABLE[i][0]) - PGM_RD_W(BEDTEMPTABLE[i - 1][0]));
  827. break;
  828. }
  829. }
  830. // Overflow: Set to last value in the table
  831. if (i == BEDTEMPTABLE_LEN) celsius = PGM_RD_W(BEDTEMPTABLE[i - 1][1]);
  832. return celsius;
  833. #elif defined(BED_USES_AD595)
  834. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN)) + TEMP_SENSOR_AD595_OFFSET;
  835. #else
  836. UNUSED(raw);
  837. return 0;
  838. #endif
  839. }
  840. /**
  841. * Get the raw values into the actual temperatures.
  842. * The raw values are created in interrupt context,
  843. * and this function is called from normal context
  844. * as it would block the stepper routine.
  845. */
  846. void Temperature::updateTemperaturesFromRawValues() {
  847. #if ENABLED(HEATER_0_USES_MAX6675)
  848. current_temperature_raw[0] = read_max6675();
  849. #endif
  850. HOTEND_LOOP()
  851. current_temperature[e] = Temperature::analog2temp(current_temperature_raw[e], e);
  852. current_temperature_bed = Temperature::analog2tempBed(current_temperature_bed_raw);
  853. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  854. redundant_temperature = Temperature::analog2temp(redundant_temperature_raw, 1);
  855. #endif
  856. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  857. filament_width_meas = analog2widthFil();
  858. #endif
  859. #if ENABLED(USE_WATCHDOG)
  860. // Reset the watchdog after we know we have a temperature measurement.
  861. watchdog_reset();
  862. #endif
  863. CRITICAL_SECTION_START;
  864. temp_meas_ready = false;
  865. CRITICAL_SECTION_END;
  866. }
  867. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  868. // Convert raw Filament Width to millimeters
  869. float Temperature::analog2widthFil() {
  870. return current_raw_filwidth * 5.0 * (1.0 / 16383.0);
  871. //return current_raw_filwidth;
  872. }
  873. // Convert raw Filament Width to a ratio
  874. int Temperature::widthFil_to_size_ratio() {
  875. float temp = filament_width_meas;
  876. if (temp < MEASURED_LOWER_LIMIT) temp = filament_width_nominal; //assume sensor cut out
  877. else NOMORE(temp, MEASURED_UPPER_LIMIT);
  878. return filament_width_nominal / temp * 100;
  879. }
  880. #endif
  881. #if ENABLED(HEATER_0_USES_MAX6675)
  882. #ifndef MAX6675_SCK_PIN
  883. #define MAX6675_SCK_PIN SCK_PIN
  884. #endif
  885. #ifndef MAX6675_DO_PIN
  886. #define MAX6675_DO_PIN MISO_PIN
  887. #endif
  888. SPI<MAX6675_DO_PIN, MOSI_PIN, MAX6675_SCK_PIN> max6675_spi;
  889. #endif
  890. /**
  891. * Initialize the temperature manager
  892. * The manager is implemented by periodic calls to manage_heater()
  893. */
  894. void Temperature::init() {
  895. #if MB(RUMBA) && (TEMP_SENSOR_0 == -1 || TEMP_SENSOR_1 == -1 || TEMP_SENSOR_2 == -1 || TEMP_SENSOR_BED == -1)
  896. // Disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
  897. MCUCR = _BV(JTD);
  898. MCUCR = _BV(JTD);
  899. #endif
  900. // Finish init of mult hotend arrays
  901. HOTEND_LOOP() maxttemp[e] = maxttemp[0];
  902. #if ENABLED(PIDTEMP) && ENABLED(PID_EXTRUSION_SCALING)
  903. last_e_position = 0;
  904. #endif
  905. #if HAS_HEATER_0
  906. SET_OUTPUT(HEATER_0_PIN);
  907. #endif
  908. #if HAS_HEATER_1
  909. SET_OUTPUT(HEATER_1_PIN);
  910. #endif
  911. #if HAS_HEATER_2
  912. SET_OUTPUT(HEATER_2_PIN);
  913. #endif
  914. #if HAS_HEATER_3
  915. SET_OUTPUT(HEATER_3_PIN);
  916. #endif
  917. #if HAS_HEATER_4
  918. SET_OUTPUT(HEATER_3_PIN);
  919. #endif
  920. #if HAS_HEATER_BED
  921. SET_OUTPUT(HEATER_BED_PIN);
  922. #endif
  923. #if HAS_FAN0
  924. SET_OUTPUT(FAN_PIN);
  925. #if ENABLED(FAST_PWM_FAN)
  926. setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  927. #endif
  928. #endif
  929. #if HAS_FAN1
  930. SET_OUTPUT(FAN1_PIN);
  931. #if ENABLED(FAST_PWM_FAN)
  932. setPwmFrequency(FAN1_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  933. #endif
  934. #endif
  935. #if HAS_FAN2
  936. SET_OUTPUT(FAN2_PIN);
  937. #if ENABLED(FAST_PWM_FAN)
  938. setPwmFrequency(FAN2_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  939. #endif
  940. #endif
  941. #if ENABLED(HEATER_0_USES_MAX6675)
  942. OUT_WRITE(SCK_PIN, LOW);
  943. OUT_WRITE(MOSI_PIN, HIGH);
  944. SET_INPUT_PULLUP(MISO_PIN);
  945. max6675_spi.init();
  946. OUT_WRITE(SS_PIN, HIGH);
  947. OUT_WRITE(MAX6675_SS, HIGH);
  948. #endif // HEATER_0_USES_MAX6675
  949. #ifdef DIDR2
  950. #define ANALOG_SELECT(pin) do{ if (pin < 8) SBI(DIDR0, pin); else SBI(DIDR2, pin - 8); }while(0)
  951. #else
  952. #define ANALOG_SELECT(pin) do{ SBI(DIDR0, pin); }while(0)
  953. #endif
  954. // Set analog inputs
  955. ADCSRA = _BV(ADEN) | _BV(ADSC) | _BV(ADIF) | 0x07;
  956. DIDR0 = 0;
  957. #ifdef DIDR2
  958. DIDR2 = 0;
  959. #endif
  960. #if HAS_TEMP_0
  961. ANALOG_SELECT(TEMP_0_PIN);
  962. #endif
  963. #if HAS_TEMP_1
  964. ANALOG_SELECT(TEMP_1_PIN);
  965. #endif
  966. #if HAS_TEMP_2
  967. ANALOG_SELECT(TEMP_2_PIN);
  968. #endif
  969. #if HAS_TEMP_3
  970. ANALOG_SELECT(TEMP_3_PIN);
  971. #endif
  972. #if HAS_TEMP_4
  973. ANALOG_SELECT(TEMP_4_PIN);
  974. #endif
  975. #if HAS_TEMP_BED
  976. ANALOG_SELECT(TEMP_BED_PIN);
  977. #endif
  978. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  979. ANALOG_SELECT(FILWIDTH_PIN);
  980. #endif
  981. #if HAS_AUTO_FAN_0
  982. #if E0_AUTO_FAN_PIN == FAN1_PIN
  983. SET_OUTPUT(E0_AUTO_FAN_PIN);
  984. #if ENABLED(FAST_PWM_FAN)
  985. setPwmFrequency(E0_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  986. #endif
  987. #else
  988. SET_OUTPUT(E0_AUTO_FAN_PIN);
  989. #endif
  990. #endif
  991. #if HAS_AUTO_FAN_1 && !AUTO_1_IS_0
  992. #if E1_AUTO_FAN_PIN == FAN1_PIN
  993. SET_OUTPUT(E1_AUTO_FAN_PIN);
  994. #if ENABLED(FAST_PWM_FAN)
  995. setPwmFrequency(E1_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  996. #endif
  997. #else
  998. SET_OUTPUT(E1_AUTO_FAN_PIN);
  999. #endif
  1000. #endif
  1001. #if HAS_AUTO_FAN_2 && !AUTO_2_IS_0 && !AUTO_2_IS_1
  1002. #if E2_AUTO_FAN_PIN == FAN1_PIN
  1003. SET_OUTPUT(E2_AUTO_FAN_PIN);
  1004. #if ENABLED(FAST_PWM_FAN)
  1005. setPwmFrequency(E2_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  1006. #endif
  1007. #else
  1008. SET_OUTPUT(E2_AUTO_FAN_PIN);
  1009. #endif
  1010. #endif
  1011. #if HAS_AUTO_FAN_3 && !AUTO_3_IS_0 && !AUTO_3_IS_1 && !AUTO_3_IS_2
  1012. #if E3_AUTO_FAN_PIN == FAN1_PIN
  1013. SET_OUTPUT(E3_AUTO_FAN_PIN);
  1014. #if ENABLED(FAST_PWM_FAN)
  1015. setPwmFrequency(E3_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  1016. #endif
  1017. #else
  1018. SET_OUTPUT(E3_AUTO_FAN_PIN);
  1019. #endif
  1020. #endif
  1021. #if HAS_AUTO_FAN_4 && !AUTO_4_IS_0 && !AUTO_4_IS_1 && !AUTO_4_IS_2 && !AUTO_4_IS_3
  1022. #if E4_AUTO_FAN_PIN == FAN1_PIN
  1023. SET_OUTPUT(E4_AUTO_FAN_PIN);
  1024. #if ENABLED(FAST_PWM_FAN)
  1025. setPwmFrequency(E4_AUTO_FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  1026. #endif
  1027. #else
  1028. SET_OUTPUT(E4_AUTO_FAN_PIN);
  1029. #endif
  1030. #endif
  1031. // Use timer0 for temperature measurement
  1032. // Interleave temperature interrupt with millies interrupt
  1033. OCR0B = 128;
  1034. SBI(TIMSK0, OCIE0B);
  1035. // Wait for temperature measurement to settle
  1036. delay(250);
  1037. #define TEMP_MIN_ROUTINE(NR) \
  1038. minttemp[NR] = HEATER_ ##NR## _MINTEMP; \
  1039. while (analog2temp(minttemp_raw[NR], NR) < HEATER_ ##NR## _MINTEMP) { \
  1040. if (HEATER_ ##NR## _RAW_LO_TEMP < HEATER_ ##NR## _RAW_HI_TEMP) \
  1041. minttemp_raw[NR] += OVERSAMPLENR; \
  1042. else \
  1043. minttemp_raw[NR] -= OVERSAMPLENR; \
  1044. }
  1045. #define TEMP_MAX_ROUTINE(NR) \
  1046. maxttemp[NR] = HEATER_ ##NR## _MAXTEMP; \
  1047. while (analog2temp(maxttemp_raw[NR], NR) > HEATER_ ##NR## _MAXTEMP) { \
  1048. if (HEATER_ ##NR## _RAW_LO_TEMP < HEATER_ ##NR## _RAW_HI_TEMP) \
  1049. maxttemp_raw[NR] -= OVERSAMPLENR; \
  1050. else \
  1051. maxttemp_raw[NR] += OVERSAMPLENR; \
  1052. }
  1053. #ifdef HEATER_0_MINTEMP
  1054. TEMP_MIN_ROUTINE(0);
  1055. #endif
  1056. #ifdef HEATER_0_MAXTEMP
  1057. TEMP_MAX_ROUTINE(0);
  1058. #endif
  1059. #if HOTENDS > 1
  1060. #ifdef HEATER_1_MINTEMP
  1061. TEMP_MIN_ROUTINE(1);
  1062. #endif
  1063. #ifdef HEATER_1_MAXTEMP
  1064. TEMP_MAX_ROUTINE(1);
  1065. #endif
  1066. #if HOTENDS > 2
  1067. #ifdef HEATER_2_MINTEMP
  1068. TEMP_MIN_ROUTINE(2);
  1069. #endif
  1070. #ifdef HEATER_2_MAXTEMP
  1071. TEMP_MAX_ROUTINE(2);
  1072. #endif
  1073. #if HOTENDS > 3
  1074. #ifdef HEATER_3_MINTEMP
  1075. TEMP_MIN_ROUTINE(3);
  1076. #endif
  1077. #ifdef HEATER_3_MAXTEMP
  1078. TEMP_MAX_ROUTINE(3);
  1079. #endif
  1080. #if HOTENDS > 4
  1081. #ifdef HEATER_4_MINTEMP
  1082. TEMP_MIN_ROUTINE(4);
  1083. #endif
  1084. #ifdef HEATER_4_MAXTEMP
  1085. TEMP_MAX_ROUTINE(4);
  1086. #endif
  1087. #endif // HOTENDS > 4
  1088. #endif // HOTENDS > 3
  1089. #endif // HOTENDS > 2
  1090. #endif // HOTENDS > 1
  1091. #ifdef BED_MINTEMP
  1092. while (analog2tempBed(bed_minttemp_raw) < BED_MINTEMP) {
  1093. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  1094. bed_minttemp_raw += OVERSAMPLENR;
  1095. #else
  1096. bed_minttemp_raw -= OVERSAMPLENR;
  1097. #endif
  1098. }
  1099. #endif // BED_MINTEMP
  1100. #ifdef BED_MAXTEMP
  1101. while (analog2tempBed(bed_maxttemp_raw) > BED_MAXTEMP) {
  1102. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  1103. bed_maxttemp_raw -= OVERSAMPLENR;
  1104. #else
  1105. bed_maxttemp_raw += OVERSAMPLENR;
  1106. #endif
  1107. }
  1108. #endif // BED_MAXTEMP
  1109. #if ENABLED(PROBING_HEATERS_OFF)
  1110. paused = false;
  1111. #endif
  1112. }
  1113. #if WATCH_HOTENDS
  1114. /**
  1115. * Start Heating Sanity Check for hotends that are below
  1116. * their target temperature by a configurable margin.
  1117. * This is called when the temperature is set. (M104, M109)
  1118. */
  1119. void Temperature::start_watching_heater(uint8_t e) {
  1120. #if HOTENDS == 1
  1121. UNUSED(e);
  1122. #endif
  1123. if (degHotend(HOTEND_INDEX) < degTargetHotend(HOTEND_INDEX) - (WATCH_TEMP_INCREASE + TEMP_HYSTERESIS + 1)) {
  1124. watch_target_temp[HOTEND_INDEX] = degHotend(HOTEND_INDEX) + WATCH_TEMP_INCREASE;
  1125. watch_heater_next_ms[HOTEND_INDEX] = millis() + (WATCH_TEMP_PERIOD) * 1000UL;
  1126. }
  1127. else
  1128. watch_heater_next_ms[HOTEND_INDEX] = 0;
  1129. }
  1130. #endif
  1131. #if WATCH_THE_BED
  1132. /**
  1133. * Start Heating Sanity Check for hotends that are below
  1134. * their target temperature by a configurable margin.
  1135. * This is called when the temperature is set. (M140, M190)
  1136. */
  1137. void Temperature::start_watching_bed() {
  1138. if (degBed() < degTargetBed() - (WATCH_BED_TEMP_INCREASE + TEMP_BED_HYSTERESIS + 1)) {
  1139. watch_target_bed_temp = degBed() + WATCH_BED_TEMP_INCREASE;
  1140. watch_bed_next_ms = millis() + (WATCH_BED_TEMP_PERIOD) * 1000UL;
  1141. }
  1142. else
  1143. watch_bed_next_ms = 0;
  1144. }
  1145. #endif
  1146. #if ENABLED(THERMAL_PROTECTION_HOTENDS) || HAS_THERMALLY_PROTECTED_BED
  1147. #if ENABLED(THERMAL_PROTECTION_HOTENDS)
  1148. Temperature::TRState Temperature::thermal_runaway_state_machine[HOTENDS] = { TRInactive };
  1149. millis_t Temperature::thermal_runaway_timer[HOTENDS] = { 0 };
  1150. #endif
  1151. #if HAS_THERMALLY_PROTECTED_BED
  1152. Temperature::TRState Temperature::thermal_runaway_bed_state_machine = TRInactive;
  1153. millis_t Temperature::thermal_runaway_bed_timer;
  1154. #endif
  1155. void Temperature::thermal_runaway_protection(Temperature::TRState* state, millis_t* timer, float current, float target, int heater_id, int period_seconds, int hysteresis_degc) {
  1156. static float tr_target_temperature[HOTENDS + 1] = { 0.0 };
  1157. /**
  1158. SERIAL_ECHO_START();
  1159. SERIAL_ECHOPGM("Thermal Thermal Runaway Running. Heater ID: ");
  1160. if (heater_id < 0) SERIAL_ECHOPGM("bed"); else SERIAL_ECHO(heater_id);
  1161. SERIAL_ECHOPAIR(" ; State:", *state);
  1162. SERIAL_ECHOPAIR(" ; Timer:", *timer);
  1163. SERIAL_ECHOPAIR(" ; Temperature:", current);
  1164. SERIAL_ECHOPAIR(" ; Target Temp:", target);
  1165. if (heater_id >= 0)
  1166. SERIAL_ECHOPAIR(" ; Idle Timeout:", heater_idle_timeout_exceeded[heater_id]);
  1167. else
  1168. SERIAL_ECHOPAIR(" ; Idle Timeout:", bed_idle_timeout_exceeded);
  1169. SERIAL_EOL();
  1170. */
  1171. const int heater_index = heater_id >= 0 ? heater_id : HOTENDS;
  1172. #if HEATER_IDLE_HANDLER
  1173. // If the heater idle timeout expires, restart
  1174. if (heater_id >= 0 && heater_idle_timeout_exceeded[heater_id]) {
  1175. *state = TRInactive;
  1176. tr_target_temperature[heater_index] = 0;
  1177. }
  1178. #if HAS_TEMP_BED
  1179. else if (heater_id < 0 && bed_idle_timeout_exceeded) {
  1180. *state = TRInactive;
  1181. tr_target_temperature[heater_index] = 0;
  1182. }
  1183. #endif
  1184. else
  1185. #endif
  1186. // If the target temperature changes, restart
  1187. if (tr_target_temperature[heater_index] != target) {
  1188. tr_target_temperature[heater_index] = target;
  1189. *state = target > 0 ? TRFirstHeating : TRInactive;
  1190. }
  1191. switch (*state) {
  1192. // Inactive state waits for a target temperature to be set
  1193. case TRInactive: break;
  1194. // When first heating, wait for the temperature to be reached then go to Stable state
  1195. case TRFirstHeating:
  1196. if (current < tr_target_temperature[heater_index]) break;
  1197. *state = TRStable;
  1198. // While the temperature is stable watch for a bad temperature
  1199. case TRStable:
  1200. if (current >= tr_target_temperature[heater_index] - hysteresis_degc) {
  1201. *timer = millis() + period_seconds * 1000UL;
  1202. break;
  1203. }
  1204. else if (PENDING(millis(), *timer)) break;
  1205. *state = TRRunaway;
  1206. case TRRunaway:
  1207. _temp_error(heater_id, PSTR(MSG_T_THERMAL_RUNAWAY), PSTR(MSG_THERMAL_RUNAWAY));
  1208. }
  1209. }
  1210. #endif // THERMAL_PROTECTION_HOTENDS || THERMAL_PROTECTION_BED
  1211. void Temperature::disable_all_heaters() {
  1212. #if ENABLED(AUTOTEMP)
  1213. planner.autotemp_enabled = false;
  1214. #endif
  1215. HOTEND_LOOP() setTargetHotend(0, e);
  1216. setTargetBed(0);
  1217. // Unpause and reset everything
  1218. #if ENABLED(PROBING_HEATERS_OFF)
  1219. pause(false);
  1220. #endif
  1221. // If all heaters go down then for sure our print job has stopped
  1222. print_job_timer.stop();
  1223. #define DISABLE_HEATER(NR) { \
  1224. setTargetHotend(0, NR); \
  1225. soft_pwm_amount[NR] = 0; \
  1226. WRITE_HEATER_ ##NR (LOW); \
  1227. }
  1228. #if HAS_TEMP_HOTEND
  1229. DISABLE_HEATER(0);
  1230. #if HOTENDS > 1
  1231. DISABLE_HEATER(1);
  1232. #if HOTENDS > 2
  1233. DISABLE_HEATER(2);
  1234. #if HOTENDS > 3
  1235. DISABLE_HEATER(3);
  1236. #if HOTENDS > 4
  1237. DISABLE_HEATER(4);
  1238. #endif // HOTENDS > 4
  1239. #endif // HOTENDS > 3
  1240. #endif // HOTENDS > 2
  1241. #endif // HOTENDS > 1
  1242. #endif
  1243. #if HAS_TEMP_BED
  1244. target_temperature_bed = 0;
  1245. soft_pwm_amount_bed = 0;
  1246. #if HAS_HEATER_BED
  1247. WRITE_HEATER_BED(LOW);
  1248. #endif
  1249. #endif
  1250. }
  1251. #if ENABLED(PROBING_HEATERS_OFF)
  1252. void Temperature::pause(const bool p) {
  1253. if (p != paused) {
  1254. paused = p;
  1255. if (p) {
  1256. HOTEND_LOOP() start_heater_idle_timer(e, 0); // timeout immediately
  1257. #if HAS_TEMP_BED
  1258. start_bed_idle_timer(0); // timeout immediately
  1259. #endif
  1260. }
  1261. else {
  1262. HOTEND_LOOP() reset_heater_idle_timer(e);
  1263. #if HAS_TEMP_BED
  1264. reset_bed_idle_timer();
  1265. #endif
  1266. }
  1267. }
  1268. }
  1269. #endif // PROBING_HEATERS_OFF
  1270. #if ENABLED(HEATER_0_USES_MAX6675)
  1271. #define MAX6675_HEAT_INTERVAL 250u
  1272. #if ENABLED(MAX6675_IS_MAX31855)
  1273. uint32_t max6675_temp = 2000;
  1274. #define MAX6675_ERROR_MASK 7
  1275. #define MAX6675_DISCARD_BITS 18
  1276. #define MAX6675_SPEED_BITS (_BV(SPR1)) // clock ÷ 64
  1277. #else
  1278. uint16_t max6675_temp = 2000;
  1279. #define MAX6675_ERROR_MASK 4
  1280. #define MAX6675_DISCARD_BITS 3
  1281. #define MAX6675_SPEED_BITS (_BV(SPR0)) // clock ÷ 16
  1282. #endif
  1283. int Temperature::read_max6675() {
  1284. static millis_t next_max6675_ms = 0;
  1285. millis_t ms = millis();
  1286. if (PENDING(ms, next_max6675_ms)) return (int)max6675_temp;
  1287. next_max6675_ms = ms + MAX6675_HEAT_INTERVAL;
  1288. CBI(
  1289. #ifdef PRR
  1290. PRR
  1291. #elif defined(PRR0)
  1292. PRR0
  1293. #endif
  1294. , PRSPI);
  1295. SPCR = _BV(MSTR) | _BV(SPE) | MAX6675_SPEED_BITS;
  1296. WRITE(MAX6675_SS, 0); // enable TT_MAX6675
  1297. // ensure 100ns delay - a bit extra is fine
  1298. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1299. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1300. // Read a big-endian temperature value
  1301. max6675_temp = 0;
  1302. for (uint8_t i = sizeof(max6675_temp); i--;) {
  1303. max6675_temp |= max6675_spi.receive();
  1304. if (i > 0) max6675_temp <<= 8; // shift left if not the last byte
  1305. }
  1306. WRITE(MAX6675_SS, 1); // disable TT_MAX6675
  1307. if (max6675_temp & MAX6675_ERROR_MASK) {
  1308. SERIAL_ERROR_START();
  1309. SERIAL_ERRORPGM("Temp measurement error! ");
  1310. #if MAX6675_ERROR_MASK == 7
  1311. SERIAL_ERRORPGM("MAX31855 ");
  1312. if (max6675_temp & 1)
  1313. SERIAL_ERRORLNPGM("Open Circuit");
  1314. else if (max6675_temp & 2)
  1315. SERIAL_ERRORLNPGM("Short to GND");
  1316. else if (max6675_temp & 4)
  1317. SERIAL_ERRORLNPGM("Short to VCC");
  1318. #else
  1319. SERIAL_ERRORLNPGM("MAX6675");
  1320. #endif
  1321. max6675_temp = MAX6675_TMAX * 4; // thermocouple open
  1322. }
  1323. else
  1324. max6675_temp >>= MAX6675_DISCARD_BITS;
  1325. #if ENABLED(MAX6675_IS_MAX31855)
  1326. // Support negative temperature
  1327. if (max6675_temp & 0x00002000) max6675_temp |= 0xFFFFC000;
  1328. #endif
  1329. return (int)max6675_temp;
  1330. }
  1331. #endif // HEATER_0_USES_MAX6675
  1332. /**
  1333. * Get raw temperatures
  1334. */
  1335. void Temperature::set_current_temp_raw() {
  1336. #if HAS_TEMP_0 && DISABLED(HEATER_0_USES_MAX6675)
  1337. current_temperature_raw[0] = raw_temp_value[0];
  1338. #endif
  1339. #if HAS_TEMP_1
  1340. #if ENABLED(TEMP_SENSOR_1_AS_REDUNDANT)
  1341. redundant_temperature_raw = raw_temp_value[1];
  1342. #else
  1343. current_temperature_raw[1] = raw_temp_value[1];
  1344. #endif
  1345. #if HAS_TEMP_2
  1346. current_temperature_raw[2] = raw_temp_value[2];
  1347. #if HAS_TEMP_3
  1348. current_temperature_raw[3] = raw_temp_value[3];
  1349. #if HAS_TEMP_4
  1350. current_temperature_raw[4] = raw_temp_value[4];
  1351. #endif
  1352. #endif
  1353. #endif
  1354. #endif
  1355. current_temperature_bed_raw = raw_temp_bed_value;
  1356. temp_meas_ready = true;
  1357. }
  1358. #if ENABLED(PINS_DEBUGGING)
  1359. /**
  1360. * monitors endstops & Z probe for changes
  1361. *
  1362. * If a change is detected then the LED is toggled and
  1363. * a message is sent out the serial port
  1364. *
  1365. * Yes, we could miss a rapid back & forth change but
  1366. * that won't matter because this is all manual.
  1367. *
  1368. */
  1369. void endstop_monitor() {
  1370. static uint16_t old_endstop_bits_local = 0;
  1371. static uint8_t local_LED_status = 0;
  1372. uint16_t current_endstop_bits_local = 0;
  1373. #if HAS_X_MIN
  1374. if (READ(X_MIN_PIN)) SBI(current_endstop_bits_local, X_MIN);
  1375. #endif
  1376. #if HAS_X_MAX
  1377. if (READ(X_MAX_PIN)) SBI(current_endstop_bits_local, X_MAX);
  1378. #endif
  1379. #if HAS_Y_MIN
  1380. if (READ(Y_MIN_PIN)) SBI(current_endstop_bits_local, Y_MIN);
  1381. #endif
  1382. #if HAS_Y_MAX
  1383. if (READ(Y_MAX_PIN)) SBI(current_endstop_bits_local, Y_MAX);
  1384. #endif
  1385. #if HAS_Z_MIN
  1386. if (READ(Z_MIN_PIN)) SBI(current_endstop_bits_local, Z_MIN);
  1387. #endif
  1388. #if HAS_Z_MAX
  1389. if (READ(Z_MAX_PIN)) SBI(current_endstop_bits_local, Z_MAX);
  1390. #endif
  1391. #if HAS_Z_MIN_PROBE_PIN
  1392. if (READ(Z_MIN_PROBE_PIN)) SBI(current_endstop_bits_local, Z_MIN_PROBE);
  1393. #endif
  1394. #if HAS_Z2_MIN
  1395. if (READ(Z2_MIN_PIN)) SBI(current_endstop_bits_local, Z2_MIN);
  1396. #endif
  1397. #if HAS_Z2_MAX
  1398. if (READ(Z2_MAX_PIN)) SBI(current_endstop_bits_local, Z2_MAX);
  1399. #endif
  1400. uint16_t endstop_change = current_endstop_bits_local ^ old_endstop_bits_local;
  1401. if (endstop_change) {
  1402. #if HAS_X_MIN
  1403. if (TEST(endstop_change, X_MIN)) SERIAL_PROTOCOLPAIR(" X_MIN:", !!TEST(current_endstop_bits_local, X_MIN));
  1404. #endif
  1405. #if HAS_X_MAX
  1406. if (TEST(endstop_change, X_MAX)) SERIAL_PROTOCOLPAIR(" X_MAX:", !!TEST(current_endstop_bits_local, X_MAX));
  1407. #endif
  1408. #if HAS_Y_MIN
  1409. if (TEST(endstop_change, Y_MIN)) SERIAL_PROTOCOLPAIR(" Y_MIN:", !!TEST(current_endstop_bits_local, Y_MIN));
  1410. #endif
  1411. #if HAS_Y_MAX
  1412. if (TEST(endstop_change, Y_MAX)) SERIAL_PROTOCOLPAIR(" Y_MAX:", !!TEST(current_endstop_bits_local, Y_MAX));
  1413. #endif
  1414. #if HAS_Z_MIN
  1415. if (TEST(endstop_change, Z_MIN)) SERIAL_PROTOCOLPAIR(" Z_MIN:", !!TEST(current_endstop_bits_local, Z_MIN));
  1416. #endif
  1417. #if HAS_Z_MAX
  1418. if (TEST(endstop_change, Z_MAX)) SERIAL_PROTOCOLPAIR(" Z_MAX:", !!TEST(current_endstop_bits_local, Z_MAX));
  1419. #endif
  1420. #if HAS_Z_MIN_PROBE_PIN
  1421. if (TEST(endstop_change, Z_MIN_PROBE)) SERIAL_PROTOCOLPAIR(" PROBE:", !!TEST(current_endstop_bits_local, Z_MIN_PROBE));
  1422. #endif
  1423. #if HAS_Z2_MIN
  1424. if (TEST(endstop_change, Z2_MIN)) SERIAL_PROTOCOLPAIR(" Z2_MIN:", !!TEST(current_endstop_bits_local, Z2_MIN));
  1425. #endif
  1426. #if HAS_Z2_MAX
  1427. if (TEST(endstop_change, Z2_MAX)) SERIAL_PROTOCOLPAIR(" Z2_MAX:", !!TEST(current_endstop_bits_local, Z2_MAX));
  1428. #endif
  1429. SERIAL_PROTOCOLPGM("\n\n");
  1430. analogWrite(LED_PIN, local_LED_status);
  1431. local_LED_status ^= 255;
  1432. old_endstop_bits_local = current_endstop_bits_local;
  1433. }
  1434. }
  1435. #endif // PINS_DEBUGGING
  1436. /**
  1437. * Timer 0 is shared with millies so don't change the prescaler.
  1438. *
  1439. * This ISR uses the compare method so it runs at the base
  1440. * frequency (16 MHz / 64 / 256 = 976.5625 Hz), but at the TCNT0 set
  1441. * in OCR0B above (128 or halfway between OVFs).
  1442. *
  1443. * - Manage PWM to all the heaters and fan
  1444. * - Prepare or Measure one of the raw ADC sensor values
  1445. * - Check new temperature values for MIN/MAX errors (kill on error)
  1446. * - Step the babysteps value for each axis towards 0
  1447. * - For PINS_DEBUGGING, monitor and report endstop pins
  1448. * - For ENDSTOP_INTERRUPTS_FEATURE check endstops if flagged
  1449. */
  1450. ISR(TIMER0_COMPB_vect) { Temperature::isr(); }
  1451. volatile bool Temperature::in_temp_isr = false;
  1452. void Temperature::isr() {
  1453. // The stepper ISR can interrupt this ISR. When it does it re-enables this ISR
  1454. // at the end of its run, potentially causing re-entry. This flag prevents it.
  1455. if (in_temp_isr) return;
  1456. in_temp_isr = true;
  1457. // Allow UART and stepper ISRs
  1458. CBI(TIMSK0, OCIE0B); //Disable Temperature ISR
  1459. sei();
  1460. static int8_t temp_count = -1;
  1461. static ADCSensorState adc_sensor_state = StartupDelay;
  1462. static uint8_t pwm_count = _BV(SOFT_PWM_SCALE);
  1463. // avoid multiple loads of pwm_count
  1464. uint8_t pwm_count_tmp = pwm_count;
  1465. #if ENABLED(ADC_KEYPAD)
  1466. static unsigned int raw_ADCKey_value = 0;
  1467. #endif
  1468. // Static members for each heater
  1469. #if ENABLED(SLOW_PWM_HEATERS)
  1470. static uint8_t slow_pwm_count = 0;
  1471. #define ISR_STATICS(n) \
  1472. static uint8_t soft_pwm_count_ ## n, \
  1473. state_heater_ ## n = 0, \
  1474. state_timer_heater_ ## n = 0
  1475. #else
  1476. #define ISR_STATICS(n) static uint8_t soft_pwm_count_ ## n = 0
  1477. #endif
  1478. // Statics per heater
  1479. ISR_STATICS(0);
  1480. #if HOTENDS > 1
  1481. ISR_STATICS(1);
  1482. #if HOTENDS > 2
  1483. ISR_STATICS(2);
  1484. #if HOTENDS > 3
  1485. ISR_STATICS(3);
  1486. #if HOTENDS > 4
  1487. ISR_STATICS(4);
  1488. #endif // HOTENDS > 4
  1489. #endif // HOTENDS > 3
  1490. #endif // HOTENDS > 2
  1491. #endif // HOTENDS > 1
  1492. #if HAS_HEATER_BED
  1493. ISR_STATICS(BED);
  1494. #endif
  1495. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1496. static unsigned long raw_filwidth_value = 0;
  1497. #endif
  1498. #if DISABLED(SLOW_PWM_HEATERS)
  1499. constexpr uint8_t pwm_mask =
  1500. #if ENABLED(SOFT_PWM_DITHER)
  1501. _BV(SOFT_PWM_SCALE) - 1
  1502. #else
  1503. 0
  1504. #endif
  1505. ;
  1506. /**
  1507. * Standard PWM modulation
  1508. */
  1509. if (pwm_count_tmp >= 127) {
  1510. pwm_count_tmp -= 127;
  1511. soft_pwm_count_0 = (soft_pwm_count_0 & pwm_mask) + soft_pwm_amount[0];
  1512. WRITE_HEATER_0(soft_pwm_count_0 > pwm_mask ? HIGH : LOW);
  1513. #if HOTENDS > 1
  1514. soft_pwm_count_1 = (soft_pwm_count_1 & pwm_mask) + soft_pwm_amount[1];
  1515. WRITE_HEATER_1(soft_pwm_count_1 > pwm_mask ? HIGH : LOW);
  1516. #if HOTENDS > 2
  1517. soft_pwm_count_2 = (soft_pwm_count_2 & pwm_mask) + soft_pwm_amount[2];
  1518. WRITE_HEATER_2(soft_pwm_count_2 > pwm_mask ? HIGH : LOW);
  1519. #if HOTENDS > 3
  1520. soft_pwm_count_3 = (soft_pwm_count_3 & pwm_mask) + soft_pwm_amount[3];
  1521. WRITE_HEATER_3(soft_pwm_count_3 > pwm_mask ? HIGH : LOW);
  1522. #if HOTENDS > 4
  1523. soft_pwm_count_4 = (soft_pwm_count_4 & pwm_mask) + soft_pwm_amount[4];
  1524. WRITE_HEATER_4(soft_pwm_count_4 > pwm_mask ? HIGH : LOW);
  1525. #endif // HOTENDS > 4
  1526. #endif // HOTENDS > 3
  1527. #endif // HOTENDS > 2
  1528. #endif // HOTENDS > 1
  1529. #if HAS_HEATER_BED
  1530. soft_pwm_count_BED = (soft_pwm_count_BED & pwm_mask) + soft_pwm_amount_bed;
  1531. WRITE_HEATER_BED(soft_pwm_count_BED > pwm_mask ? HIGH : LOW);
  1532. #endif
  1533. #if ENABLED(FAN_SOFT_PWM)
  1534. #if HAS_FAN0
  1535. soft_pwm_count_fan[0] = (soft_pwm_count_fan[0] & pwm_mask) + (soft_pwm_amount_fan[0] >> 1);
  1536. WRITE_FAN(soft_pwm_count_fan[0] > pwm_mask ? HIGH : LOW);
  1537. #endif
  1538. #if HAS_FAN1
  1539. soft_pwm_count_fan[1] = (soft_pwm_count_fan[1] & pwm_mask) + (soft_pwm_amount_fan[1] >> 1);
  1540. WRITE_FAN1(soft_pwm_count_fan[1] > pwm_mask ? HIGH : LOW);
  1541. #endif
  1542. #if HAS_FAN2
  1543. soft_pwm_count_fan[2] = (soft_pwm_count_fan[2] & pwm_mask) + (soft_pwm_amount_fan[2] >> 1);
  1544. WRITE_FAN2(soft_pwm_count_fan[2] > pwm_mask ? HIGH : LOW);
  1545. #endif
  1546. #endif
  1547. }
  1548. else {
  1549. if (soft_pwm_count_0 <= pwm_count_tmp) WRITE_HEATER_0(LOW);
  1550. #if HOTENDS > 1
  1551. if (soft_pwm_count_1 <= pwm_count_tmp) WRITE_HEATER_1(LOW);
  1552. #if HOTENDS > 2
  1553. if (soft_pwm_count_2 <= pwm_count_tmp) WRITE_HEATER_2(LOW);
  1554. #if HOTENDS > 3
  1555. if (soft_pwm_count_3 <= pwm_count_tmp) WRITE_HEATER_3(LOW);
  1556. #if HOTENDS > 4
  1557. if (soft_pwm_count_4 <= pwm_count_tmp) WRITE_HEATER_4(LOW);
  1558. #endif // HOTENDS > 4
  1559. #endif // HOTENDS > 3
  1560. #endif // HOTENDS > 2
  1561. #endif // HOTENDS > 1
  1562. #if HAS_HEATER_BED
  1563. if (soft_pwm_count_BED <= pwm_count_tmp) WRITE_HEATER_BED(LOW);
  1564. #endif
  1565. #if ENABLED(FAN_SOFT_PWM)
  1566. #if HAS_FAN0
  1567. if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(LOW);
  1568. #endif
  1569. #if HAS_FAN1
  1570. if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN1(LOW);
  1571. #endif
  1572. #if HAS_FAN2
  1573. if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN2(LOW);
  1574. #endif
  1575. #endif
  1576. }
  1577. // SOFT_PWM_SCALE to frequency:
  1578. //
  1579. // 0: 16000000/64/256/128 = 7.6294 Hz
  1580. // 1: / 64 = 15.2588 Hz
  1581. // 2: / 32 = 30.5176 Hz
  1582. // 3: / 16 = 61.0352 Hz
  1583. // 4: / 8 = 122.0703 Hz
  1584. // 5: / 4 = 244.1406 Hz
  1585. pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
  1586. #else // SLOW_PWM_HEATERS
  1587. /**
  1588. * SLOW PWM HEATERS
  1589. *
  1590. * For relay-driven heaters
  1591. */
  1592. #ifndef MIN_STATE_TIME
  1593. #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
  1594. #endif
  1595. // Macros for Slow PWM timer logic
  1596. #define _SLOW_PWM_ROUTINE(NR, src) \
  1597. soft_pwm_count_ ##NR = src; \
  1598. if (soft_pwm_count_ ##NR > 0) { \
  1599. if (state_timer_heater_ ##NR == 0) { \
  1600. if (state_heater_ ##NR == 0) state_timer_heater_ ##NR = MIN_STATE_TIME; \
  1601. state_heater_ ##NR = 1; \
  1602. WRITE_HEATER_ ##NR(1); \
  1603. } \
  1604. } \
  1605. else { \
  1606. if (state_timer_heater_ ##NR == 0) { \
  1607. if (state_heater_ ##NR == 1) state_timer_heater_ ##NR = MIN_STATE_TIME; \
  1608. state_heater_ ##NR = 0; \
  1609. WRITE_HEATER_ ##NR(0); \
  1610. } \
  1611. }
  1612. #define SLOW_PWM_ROUTINE(n) _SLOW_PWM_ROUTINE(n, soft_pwm_amount[n])
  1613. #define PWM_OFF_ROUTINE(NR) \
  1614. if (soft_pwm_count_ ##NR < slow_pwm_count) { \
  1615. if (state_timer_heater_ ##NR == 0) { \
  1616. if (state_heater_ ##NR == 1) state_timer_heater_ ##NR = MIN_STATE_TIME; \
  1617. state_heater_ ##NR = 0; \
  1618. WRITE_HEATER_ ##NR (0); \
  1619. } \
  1620. }
  1621. if (slow_pwm_count == 0) {
  1622. SLOW_PWM_ROUTINE(0);
  1623. #if HOTENDS > 1
  1624. SLOW_PWM_ROUTINE(1);
  1625. #if HOTENDS > 2
  1626. SLOW_PWM_ROUTINE(2);
  1627. #if HOTENDS > 3
  1628. SLOW_PWM_ROUTINE(3);
  1629. #if HOTENDS > 4
  1630. SLOW_PWM_ROUTINE(4);
  1631. #endif // HOTENDS > 4
  1632. #endif // HOTENDS > 3
  1633. #endif // HOTENDS > 2
  1634. #endif // HOTENDS > 1
  1635. #if HAS_HEATER_BED
  1636. _SLOW_PWM_ROUTINE(BED, soft_pwm_amount_bed); // BED
  1637. #endif
  1638. } // slow_pwm_count == 0
  1639. PWM_OFF_ROUTINE(0);
  1640. #if HOTENDS > 1
  1641. PWM_OFF_ROUTINE(1);
  1642. #if HOTENDS > 2
  1643. PWM_OFF_ROUTINE(2);
  1644. #if HOTENDS > 3
  1645. PWM_OFF_ROUTINE(3);
  1646. #if HOTENDS > 4
  1647. PWM_OFF_ROUTINE(4);
  1648. #endif // HOTENDS > 4
  1649. #endif // HOTENDS > 3
  1650. #endif // HOTENDS > 2
  1651. #endif // HOTENDS > 1
  1652. #if HAS_HEATER_BED
  1653. PWM_OFF_ROUTINE(BED); // BED
  1654. #endif
  1655. #if ENABLED(FAN_SOFT_PWM)
  1656. if (pwm_count_tmp >= 127) {
  1657. pwm_count_tmp = 0;
  1658. #if HAS_FAN0
  1659. soft_pwm_count_fan[0] = soft_pwm_amount_fan[0] >> 1;
  1660. WRITE_FAN(soft_pwm_count_fan[0] > 0 ? HIGH : LOW);
  1661. #endif
  1662. #if HAS_FAN1
  1663. soft_pwm_count_fan[1] = soft_pwm_amount_fan[1] >> 1;
  1664. WRITE_FAN1(soft_pwm_count_fan[1] > 0 ? HIGH : LOW);
  1665. #endif
  1666. #if HAS_FAN2
  1667. soft_pwm_count_fan[2] = soft_pwm_amount_fan[2] >> 1;
  1668. WRITE_FAN2(soft_pwm_count_fan[2] > 0 ? HIGH : LOW);
  1669. #endif
  1670. }
  1671. #if HAS_FAN0
  1672. if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(LOW);
  1673. #endif
  1674. #if HAS_FAN1
  1675. if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN1(LOW);
  1676. #endif
  1677. #if HAS_FAN2
  1678. if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN2(LOW);
  1679. #endif
  1680. #endif // FAN_SOFT_PWM
  1681. // SOFT_PWM_SCALE to frequency:
  1682. //
  1683. // 0: 16000000/64/256/128 = 7.6294 Hz
  1684. // 1: / 64 = 15.2588 Hz
  1685. // 2: / 32 = 30.5176 Hz
  1686. // 3: / 16 = 61.0352 Hz
  1687. // 4: / 8 = 122.0703 Hz
  1688. // 5: / 4 = 244.1406 Hz
  1689. pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE);
  1690. // increment slow_pwm_count only every 64th pwm_count,
  1691. // i.e. yielding a PWM frequency of 16/128 Hz (8s).
  1692. if (((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0) {
  1693. slow_pwm_count++;
  1694. slow_pwm_count &= 0x7F;
  1695. if (state_timer_heater_0 > 0) state_timer_heater_0--;
  1696. #if HOTENDS > 1
  1697. if (state_timer_heater_1 > 0) state_timer_heater_1--;
  1698. #if HOTENDS > 2
  1699. if (state_timer_heater_2 > 0) state_timer_heater_2--;
  1700. #if HOTENDS > 3
  1701. if (state_timer_heater_3 > 0) state_timer_heater_3--;
  1702. #if HOTENDS > 4
  1703. if (state_timer_heater_4 > 0) state_timer_heater_4--;
  1704. #endif // HOTENDS > 4
  1705. #endif // HOTENDS > 3
  1706. #endif // HOTENDS > 2
  1707. #endif // HOTENDS > 1
  1708. #if HAS_HEATER_BED
  1709. if (state_timer_heater_BED > 0) state_timer_heater_BED--;
  1710. #endif
  1711. } // ((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0
  1712. #endif // SLOW_PWM_HEATERS
  1713. //
  1714. // Update lcd buttons 488 times per second
  1715. //
  1716. static bool do_buttons;
  1717. if ((do_buttons ^= true)) lcd_buttons_update();
  1718. /**
  1719. * One sensor is sampled on every other call of the ISR.
  1720. * Each sensor is read 16 (OVERSAMPLENR) times, taking the average.
  1721. *
  1722. * On each Prepare pass, ADC is started for a sensor pin.
  1723. * On the next pass, the ADC value is read and accumulated.
  1724. *
  1725. * This gives each ADC 0.9765ms to charge up.
  1726. */
  1727. #define SET_ADMUX_ADCSRA(pin) ADMUX = _BV(REFS0) | (pin & 0x07); SBI(ADCSRA, ADSC)
  1728. #ifdef MUX5
  1729. #define START_ADC(pin) if (pin > 7) ADCSRB = _BV(MUX5); else ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
  1730. #else
  1731. #define START_ADC(pin) ADCSRB = 0; SET_ADMUX_ADCSRA(pin)
  1732. #endif
  1733. switch (adc_sensor_state) {
  1734. case SensorsReady: {
  1735. // All sensors have been read. Stay in this state for a few
  1736. // ISRs to save on calls to temp update/checking code below.
  1737. constexpr int8_t extra_loops = MIN_ADC_ISR_LOOPS - (int8_t)SensorsReady;
  1738. static uint8_t delay_count = 0;
  1739. if (extra_loops > 0) {
  1740. if (delay_count == 0) delay_count = extra_loops; // Init this delay
  1741. if (--delay_count) // While delaying...
  1742. adc_sensor_state = (ADCSensorState)(int(SensorsReady) - 1); // retain this state (else, next state will be 0)
  1743. break;
  1744. }
  1745. else
  1746. adc_sensor_state = (ADCSensorState)0; // Fall-through to start first sensor now
  1747. }
  1748. #if HAS_TEMP_0
  1749. case PrepareTemp_0:
  1750. START_ADC(TEMP_0_PIN);
  1751. break;
  1752. case MeasureTemp_0:
  1753. raw_temp_value[0] += ADC;
  1754. break;
  1755. #endif
  1756. #if HAS_TEMP_BED
  1757. case PrepareTemp_BED:
  1758. START_ADC(TEMP_BED_PIN);
  1759. break;
  1760. case MeasureTemp_BED:
  1761. raw_temp_bed_value += ADC;
  1762. break;
  1763. #endif
  1764. #if HAS_TEMP_1
  1765. case PrepareTemp_1:
  1766. START_ADC(TEMP_1_PIN);
  1767. break;
  1768. case MeasureTemp_1:
  1769. raw_temp_value[1] += ADC;
  1770. break;
  1771. #endif
  1772. #if HAS_TEMP_2
  1773. case PrepareTemp_2:
  1774. START_ADC(TEMP_2_PIN);
  1775. break;
  1776. case MeasureTemp_2:
  1777. raw_temp_value[2] += ADC;
  1778. break;
  1779. #endif
  1780. #if HAS_TEMP_3
  1781. case PrepareTemp_3:
  1782. START_ADC(TEMP_3_PIN);
  1783. break;
  1784. case MeasureTemp_3:
  1785. raw_temp_value[3] += ADC;
  1786. break;
  1787. #endif
  1788. #if HAS_TEMP_4
  1789. case PrepareTemp_4:
  1790. START_ADC(TEMP_4_PIN);
  1791. break;
  1792. case MeasureTemp_4:
  1793. raw_temp_value[4] += ADC;
  1794. break;
  1795. #endif
  1796. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1797. case Prepare_FILWIDTH:
  1798. START_ADC(FILWIDTH_PIN);
  1799. break;
  1800. case Measure_FILWIDTH:
  1801. if (ADC > 102) { // Make sure ADC is reading > 0.5 volts, otherwise don't read.
  1802. raw_filwidth_value -= (raw_filwidth_value >> 7); // Subtract 1/128th of the raw_filwidth_value
  1803. raw_filwidth_value += ((unsigned long)ADC << 7); // Add new ADC reading, scaled by 128
  1804. }
  1805. break;
  1806. #endif
  1807. #if ENABLED(ADC_KEYPAD)
  1808. case Prepare_ADC_KEY:
  1809. START_ADC(ADC_KEYPAD_PIN);
  1810. break;
  1811. case Measure_ADC_KEY:
  1812. if (ADCKey_count < 16) {
  1813. raw_ADCKey_value = ADC;
  1814. if (raw_ADCKey_value > 900) {
  1815. //ADC Key release
  1816. ADCKey_count = 0;
  1817. current_ADCKey_raw = 0;
  1818. }
  1819. else {
  1820. current_ADCKey_raw += raw_ADCKey_value;
  1821. ADCKey_count++;
  1822. }
  1823. }
  1824. break;
  1825. #endif // ADC_KEYPAD
  1826. case StartupDelay: break;
  1827. } // switch(adc_sensor_state)
  1828. if (!adc_sensor_state && ++temp_count >= OVERSAMPLENR) { // 10 * 16 * 1/(16000000/64/256) = 164ms.
  1829. temp_count = 0;
  1830. // Update the raw values if they've been read. Else we could be updating them during reading.
  1831. if (!temp_meas_ready) set_current_temp_raw();
  1832. // Filament Sensor - can be read any time since IIR filtering is used
  1833. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1834. current_raw_filwidth = raw_filwidth_value >> 10; // Divide to get to 0-16384 range since we used 1/128 IIR filter approach
  1835. #endif
  1836. ZERO(raw_temp_value);
  1837. raw_temp_bed_value = 0;
  1838. #define TEMPDIR(N) ((HEATER_##N##_RAW_LO_TEMP) > (HEATER_##N##_RAW_HI_TEMP) ? -1 : 1)
  1839. int constexpr temp_dir[] = {
  1840. #if ENABLED(HEATER_0_USES_MAX6675)
  1841. 0
  1842. #else
  1843. TEMPDIR(0)
  1844. #endif
  1845. #if HOTENDS > 1
  1846. , TEMPDIR(1)
  1847. #if HOTENDS > 2
  1848. , TEMPDIR(2)
  1849. #if HOTENDS > 3
  1850. , TEMPDIR(3)
  1851. #if HOTENDS > 4
  1852. , TEMPDIR(4)
  1853. #endif // HOTENDS > 4
  1854. #endif // HOTENDS > 3
  1855. #endif // HOTENDS > 2
  1856. #endif // HOTENDS > 1
  1857. };
  1858. for (uint8_t e = 0; e < COUNT(temp_dir); e++) {
  1859. const int16_t tdir = temp_dir[e], rawtemp = current_temperature_raw[e] * tdir;
  1860. const bool heater_on = 0 <
  1861. #if ENABLED(PIDTEMP)
  1862. soft_pwm_amount[e]
  1863. #else
  1864. target_temperature[e]
  1865. #endif
  1866. ;
  1867. if (rawtemp > maxttemp_raw[e] * tdir && heater_on) max_temp_error(e);
  1868. if (rawtemp < minttemp_raw[e] * tdir && !is_preheating(e) && heater_on) {
  1869. #ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
  1870. if (++consecutive_low_temperature_error[e] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)
  1871. #endif
  1872. min_temp_error(e);
  1873. }
  1874. #ifdef MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED
  1875. else
  1876. consecutive_low_temperature_error[e] = 0;
  1877. #endif
  1878. }
  1879. #if HAS_TEMP_BED
  1880. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1881. #define GEBED <=
  1882. #else
  1883. #define GEBED >=
  1884. #endif
  1885. const bool bed_on = 0 <
  1886. #if ENABLED(PIDTEMPBED)
  1887. soft_pwm_amount_bed
  1888. #else
  1889. target_temperature_bed
  1890. #endif
  1891. ;
  1892. if (current_temperature_bed_raw GEBED bed_maxttemp_raw && bed_on) max_temp_error(-1);
  1893. if (bed_minttemp_raw GEBED current_temperature_bed_raw && bed_on) min_temp_error(-1);
  1894. #endif
  1895. } // temp_count >= OVERSAMPLENR
  1896. // Go to the next state, up to SensorsReady
  1897. adc_sensor_state = (ADCSensorState)(int(adc_sensor_state) + 1);
  1898. if (adc_sensor_state > SensorsReady) adc_sensor_state = (ADCSensorState)0;
  1899. #if ENABLED(BABYSTEPPING)
  1900. LOOP_XYZ(axis) {
  1901. const int curTodo = babystepsTodo[axis]; // get rid of volatile for performance
  1902. if (curTodo) {
  1903. stepper.babystep((AxisEnum)axis, curTodo > 0);
  1904. if (curTodo > 0) babystepsTodo[axis]--;
  1905. else babystepsTodo[axis]++;
  1906. }
  1907. }
  1908. #endif // BABYSTEPPING
  1909. #if ENABLED(PINS_DEBUGGING)
  1910. extern bool endstop_monitor_flag;
  1911. // run the endstop monitor at 15Hz
  1912. static uint8_t endstop_monitor_count = 16; // offset this check from the others
  1913. if (endstop_monitor_flag) {
  1914. endstop_monitor_count += _BV(1); // 15 Hz
  1915. endstop_monitor_count &= 0x7F;
  1916. if (!endstop_monitor_count) endstop_monitor(); // report changes in endstop status
  1917. }
  1918. #endif
  1919. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  1920. extern volatile uint8_t e_hit;
  1921. if (e_hit && ENDSTOPS_ENABLED) {
  1922. endstops.update(); // call endstop update routine
  1923. e_hit--;
  1924. }
  1925. #endif
  1926. cli();
  1927. in_temp_isr = false;
  1928. SBI(TIMSK0, OCIE0B); //re-enable Temperature ISR
  1929. }