temperature.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038
  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 "SdFatUtil.h"
  30. #include <avr/wdt.h>
  31. #include "adc.h"
  32. #include "ConfigurationStore.h"
  33. #include "Timer.h"
  34. #include "Configuration_prusa.h"
  35. #if (ADC_OVRSAMPL != OVERSAMPLENR)
  36. #error "ADC_OVRSAMPL oversampling must match OVERSAMPLENR"
  37. #endif
  38. //===========================================================================
  39. //=============================public variables============================
  40. //===========================================================================
  41. int target_temperature[EXTRUDERS] = { 0 };
  42. int target_temperature_bed = 0;
  43. int current_temperature_raw[EXTRUDERS] = { 0 };
  44. float current_temperature[EXTRUDERS] = { 0.0 };
  45. #ifdef PINDA_THERMISTOR
  46. uint16_t current_temperature_raw_pinda = 0 ; //value with more averaging applied
  47. uint16_t current_temperature_raw_pinda_fast = 0; //value read from adc
  48. float current_temperature_pinda = 0.0;
  49. #endif //PINDA_THERMISTOR
  50. #ifdef AMBIENT_THERMISTOR
  51. int current_temperature_raw_ambient = 0 ;
  52. float current_temperature_ambient = 0.0;
  53. #endif //AMBIENT_THERMISTOR
  54. #ifdef VOLT_PWR_PIN
  55. int current_voltage_raw_pwr = 0;
  56. #endif
  57. #ifdef VOLT_BED_PIN
  58. int current_voltage_raw_bed = 0;
  59. #endif
  60. #ifdef IR_SENSOR_ANALOG
  61. uint16_t current_voltage_raw_IR = 0;
  62. #endif //IR_SENSOR_ANALOG
  63. int current_temperature_bed_raw = 0;
  64. float current_temperature_bed = 0.0;
  65. #ifdef PIDTEMP
  66. float _Kp, _Ki, _Kd;
  67. int pid_cycle, pid_number_of_cycles;
  68. bool pid_tuning_finished = false;
  69. #endif //PIDTEMP
  70. unsigned char soft_pwm_bed;
  71. #ifdef BABYSTEPPING
  72. volatile int babystepsTodo[3]={0,0,0};
  73. #endif
  74. //===========================================================================
  75. //=============================private variables============================
  76. //===========================================================================
  77. #define TEMP_MEAS_RATE 250
  78. static volatile bool temp_meas_ready = false;
  79. #ifdef PIDTEMP
  80. //static cannot be external:
  81. static float iState_sum[EXTRUDERS] = { 0 };
  82. static float dState_last[EXTRUDERS] = { 0 };
  83. static float pTerm[EXTRUDERS];
  84. static float iTerm[EXTRUDERS];
  85. static float dTerm[EXTRUDERS];
  86. //int output;
  87. static float pid_error[EXTRUDERS];
  88. static float iState_sum_min[EXTRUDERS];
  89. static float iState_sum_max[EXTRUDERS];
  90. // static float pid_input[EXTRUDERS];
  91. // static float pid_output[EXTRUDERS];
  92. static bool pid_reset[EXTRUDERS];
  93. #endif //PIDTEMP
  94. #ifdef PIDTEMPBED
  95. //static cannot be external:
  96. static float temp_iState_bed = { 0 };
  97. static float temp_dState_bed = { 0 };
  98. static float pTerm_bed;
  99. static float iTerm_bed;
  100. static float dTerm_bed;
  101. //int output;
  102. static float pid_error_bed;
  103. static float temp_iState_min_bed;
  104. static float temp_iState_max_bed;
  105. #else //PIDTEMPBED
  106. static unsigned long previous_millis_bed_heater;
  107. #endif //PIDTEMPBED
  108. static unsigned char soft_pwm[EXTRUDERS];
  109. #ifdef FAN_SOFT_PWM
  110. unsigned char fanSpeedSoftPwm;
  111. static unsigned char soft_pwm_fan;
  112. #endif
  113. uint8_t fanSpeedBckp = 255;
  114. #if EXTRUDERS > 3
  115. # error Unsupported number of extruders
  116. #elif EXTRUDERS > 2
  117. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1, v2, v3 }
  118. #elif EXTRUDERS > 1
  119. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1, v2 }
  120. #else
  121. # define ARRAY_BY_EXTRUDERS(v1, v2, v3) { v1 }
  122. #endif
  123. static ShortTimer oTimer4minTempHeater,oTimer4minTempBed;
  124. // Init min and max temp with extreme values to prevent false errors during startup
  125. static int minttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_RAW_LO_TEMP , HEATER_1_RAW_LO_TEMP , HEATER_2_RAW_LO_TEMP );
  126. static int maxttemp_raw[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_RAW_HI_TEMP , HEATER_1_RAW_HI_TEMP , HEATER_2_RAW_HI_TEMP );
  127. static int minttemp[EXTRUDERS] = ARRAY_BY_EXTRUDERS( 0, 0, 0 );
  128. static int maxttemp[EXTRUDERS] = ARRAY_BY_EXTRUDERS( 16383, 16383, 16383 );
  129. #ifdef BED_MINTEMP
  130. static int bed_minttemp_raw = HEATER_BED_RAW_LO_TEMP;
  131. #endif
  132. #ifdef BED_MAXTEMP
  133. static int bed_maxttemp_raw = HEATER_BED_RAW_HI_TEMP;
  134. #endif
  135. #ifdef AMBIENT_MINTEMP
  136. static int ambient_minttemp_raw = AMBIENT_RAW_LO_TEMP;
  137. #endif
  138. #ifdef AMBIENT_MAXTEMP
  139. static int ambient_maxttemp_raw = AMBIENT_RAW_HI_TEMP;
  140. #endif
  141. static void *heater_ttbl_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS( (void *)HEATER_0_TEMPTABLE, (void *)HEATER_1_TEMPTABLE, (void *)HEATER_2_TEMPTABLE );
  142. static uint8_t heater_ttbllen_map[EXTRUDERS] = ARRAY_BY_EXTRUDERS( HEATER_0_TEMPTABLE_LEN, HEATER_1_TEMPTABLE_LEN, HEATER_2_TEMPTABLE_LEN );
  143. static float analog2temp(int raw, uint8_t e);
  144. static float analog2tempBed(int raw);
  145. #ifdef AMBIENT_MAXTEMP
  146. static float analog2tempAmbient(int raw);
  147. #endif
  148. static void updateTemperaturesFromRawValues();
  149. enum TempRunawayStates : uint8_t
  150. {
  151. TempRunaway_INACTIVE = 0,
  152. TempRunaway_PREHEAT = 1,
  153. TempRunaway_ACTIVE = 2,
  154. };
  155. #ifndef SOFT_PWM_SCALE
  156. #define SOFT_PWM_SCALE 0
  157. #endif
  158. //===========================================================================
  159. //============================= functions ============================
  160. //===========================================================================
  161. #if (defined (TEMP_RUNAWAY_BED_HYSTERESIS) && TEMP_RUNAWAY_BED_TIMEOUT > 0) || (defined (TEMP_RUNAWAY_EXTRUDER_HYSTERESIS) && TEMP_RUNAWAY_EXTRUDER_TIMEOUT > 0)
  162. static uint8_t temp_runaway_status[1 + EXTRUDERS];
  163. static float temp_runaway_target[1 + EXTRUDERS];
  164. static uint32_t temp_runaway_timer[1 + EXTRUDERS];
  165. static uint16_t temp_runaway_error_counter[1 + EXTRUDERS];
  166. static void temp_runaway_check(uint8_t _heater_id, float _target_temperature, float _current_temperature, float _output, bool _isbed);
  167. static void temp_runaway_stop(bool isPreheat, bool isBed);
  168. #endif
  169. // return "false", if all extruder-heaters are 'off' (ie. "true", if any heater is 'on')
  170. bool checkAllHotends(void)
  171. {
  172. bool result=false;
  173. for(int i=0;i<EXTRUDERS;i++) result=(result||(target_temperature[i]!=0));
  174. return(result);
  175. }
  176. // WARNING: the following function has been marked noinline to avoid a GCC 4.9.2 LTO
  177. // codegen bug causing a stack overwrite issue in process_commands()
  178. void __attribute__((noinline)) PID_autotune(float temp, int extruder, int ncycles)
  179. {
  180. pid_number_of_cycles = ncycles;
  181. pid_tuning_finished = false;
  182. float input = 0.0;
  183. pid_cycle=0;
  184. bool heating = true;
  185. unsigned long temp_millis = _millis();
  186. unsigned long t1=temp_millis;
  187. unsigned long t2=temp_millis;
  188. long t_high = 0;
  189. long t_low = 0;
  190. long bias, d;
  191. float Ku, Tu;
  192. float max = 0, min = 10000;
  193. uint8_t safety_check_cycles = 0;
  194. const uint8_t safety_check_cycles_count = (extruder < 0) ? 45 : 10; //10 cycles / 20s delay for extruder and 45 cycles / 90s for heatbed
  195. float temp_ambient;
  196. #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1)
  197. unsigned long extruder_autofan_last_check = _millis();
  198. #endif
  199. if ((extruder >= EXTRUDERS)
  200. #if (TEMP_BED_PIN <= -1)
  201. ||(extruder < 0)
  202. #endif
  203. ){
  204. SERIAL_ECHOLN("PID Autotune failed. Bad extruder number.");
  205. pid_tuning_finished = true;
  206. pid_cycle = 0;
  207. return;
  208. }
  209. SERIAL_ECHOLN("PID Autotune start");
  210. disable_heater(); // switch off all heaters.
  211. if (extruder<0)
  212. {
  213. soft_pwm_bed = (MAX_BED_POWER)/2;
  214. timer02_set_pwm0(soft_pwm_bed << 1);
  215. bias = d = (MAX_BED_POWER)/2;
  216. target_temperature_bed = (int)temp; // to display the requested target bed temperature properly on the main screen
  217. }
  218. else
  219. {
  220. soft_pwm[extruder] = (PID_MAX)/2;
  221. bias = d = (PID_MAX)/2;
  222. target_temperature[extruder] = (int)temp; // to display the requested target extruder temperature properly on the main screen
  223. }
  224. for(;;) {
  225. #ifdef WATCHDOG
  226. wdt_reset();
  227. #endif //WATCHDOG
  228. if(temp_meas_ready == true) { // temp sample ready
  229. updateTemperaturesFromRawValues();
  230. input = (extruder<0)?current_temperature_bed:current_temperature[extruder];
  231. max=max(max,input);
  232. min=min(min,input);
  233. #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1)
  234. if(_millis() - extruder_autofan_last_check > 2500) {
  235. checkExtruderAutoFans();
  236. extruder_autofan_last_check = _millis();
  237. }
  238. #endif
  239. if(heating == true && input > temp) {
  240. if(_millis() - t2 > 5000) {
  241. heating=false;
  242. if (extruder<0)
  243. {
  244. soft_pwm_bed = (bias - d) >> 1;
  245. timer02_set_pwm0(soft_pwm_bed << 1);
  246. }
  247. else
  248. soft_pwm[extruder] = (bias - d) >> 1;
  249. t1=_millis();
  250. t_high=t1 - t2;
  251. max=temp;
  252. }
  253. }
  254. if(heating == false && input < temp) {
  255. if(_millis() - t1 > 5000) {
  256. heating=true;
  257. t2=_millis();
  258. t_low=t2 - t1;
  259. if(pid_cycle > 0) {
  260. bias += (d*(t_high - t_low))/(t_low + t_high);
  261. bias = constrain(bias, 20 ,(extruder<0?(MAX_BED_POWER):(PID_MAX))-20);
  262. if(bias > (extruder<0?(MAX_BED_POWER):(PID_MAX))/2) d = (extruder<0?(MAX_BED_POWER):(PID_MAX)) - 1 - bias;
  263. else d = bias;
  264. SERIAL_PROTOCOLPGM(" bias: "); SERIAL_PROTOCOL(bias);
  265. SERIAL_PROTOCOLPGM(" d: "); SERIAL_PROTOCOL(d);
  266. SERIAL_PROTOCOLPGM(" min: "); SERIAL_PROTOCOL(min);
  267. SERIAL_PROTOCOLPGM(" max: "); SERIAL_PROTOCOLLN(max);
  268. if(pid_cycle > 2) {
  269. Ku = (4.0*d)/(3.14159*(max-min)/2.0);
  270. Tu = ((float)(t_low + t_high)/1000.0);
  271. SERIAL_PROTOCOLPGM(" Ku: "); SERIAL_PROTOCOL(Ku);
  272. SERIAL_PROTOCOLPGM(" Tu: "); SERIAL_PROTOCOLLN(Tu);
  273. _Kp = 0.6*Ku;
  274. _Ki = 2*_Kp/Tu;
  275. _Kd = _Kp*Tu/8;
  276. SERIAL_PROTOCOLLNPGM(" Classic PID ");
  277. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  278. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  279. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  280. /*
  281. _Kp = 0.33*Ku;
  282. _Ki = _Kp/Tu;
  283. _Kd = _Kp*Tu/3;
  284. SERIAL_PROTOCOLLNPGM(" Some overshoot ");
  285. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  286. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  287. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  288. _Kp = 0.2*Ku;
  289. _Ki = 2*_Kp/Tu;
  290. _Kd = _Kp*Tu/3;
  291. SERIAL_PROTOCOLLNPGM(" No overshoot ");
  292. SERIAL_PROTOCOLPGM(" Kp: "); SERIAL_PROTOCOLLN(_Kp);
  293. SERIAL_PROTOCOLPGM(" Ki: "); SERIAL_PROTOCOLLN(_Ki);
  294. SERIAL_PROTOCOLPGM(" Kd: "); SERIAL_PROTOCOLLN(_Kd);
  295. */
  296. }
  297. }
  298. if (extruder<0)
  299. {
  300. soft_pwm_bed = (bias + d) >> 1;
  301. timer02_set_pwm0(soft_pwm_bed << 1);
  302. }
  303. else
  304. soft_pwm[extruder] = (bias + d) >> 1;
  305. pid_cycle++;
  306. min=temp;
  307. }
  308. }
  309. }
  310. if(input > (temp + 20)) {
  311. SERIAL_PROTOCOLLNPGM("PID Autotune failed! Temperature too high");
  312. pid_tuning_finished = true;
  313. pid_cycle = 0;
  314. return;
  315. }
  316. if(_millis() - temp_millis > 2000) {
  317. int p;
  318. if (extruder<0){
  319. p=soft_pwm_bed;
  320. SERIAL_PROTOCOLPGM("B:");
  321. }else{
  322. p=soft_pwm[extruder];
  323. SERIAL_PROTOCOLPGM("T:");
  324. }
  325. SERIAL_PROTOCOL(input);
  326. SERIAL_PROTOCOLPGM(" @:");
  327. SERIAL_PROTOCOLLN(p);
  328. if (safety_check_cycles == 0) { //save ambient temp
  329. temp_ambient = input;
  330. //SERIAL_ECHOPGM("Ambient T: ");
  331. //MYSERIAL.println(temp_ambient);
  332. safety_check_cycles++;
  333. }
  334. else if (safety_check_cycles < safety_check_cycles_count) { //delay
  335. safety_check_cycles++;
  336. }
  337. else if (safety_check_cycles == safety_check_cycles_count){ //check that temperature is rising
  338. safety_check_cycles++;
  339. //SERIAL_ECHOPGM("Time from beginning: ");
  340. //MYSERIAL.print(safety_check_cycles_count * 2);
  341. //SERIAL_ECHOPGM("s. Difference between current and ambient T: ");
  342. //MYSERIAL.println(input - temp_ambient);
  343. if (fabs(input - temp_ambient) < 5.0) {
  344. temp_runaway_stop(false, (extruder<0));
  345. pid_tuning_finished = true;
  346. return;
  347. }
  348. }
  349. temp_millis = _millis();
  350. }
  351. if(((_millis() - t1) + (_millis() - t2)) > (10L*60L*1000L*2L)) {
  352. SERIAL_PROTOCOLLNPGM("PID Autotune failed! timeout");
  353. pid_tuning_finished = true;
  354. pid_cycle = 0;
  355. return;
  356. }
  357. if(pid_cycle > ncycles) {
  358. SERIAL_PROTOCOLLNPGM("PID Autotune finished! Put the last Kp, Ki and Kd constants from above into Configuration.h");
  359. pid_tuning_finished = true;
  360. pid_cycle = 0;
  361. return;
  362. }
  363. lcd_update(0);
  364. }
  365. }
  366. void updatePID()
  367. {
  368. #ifdef PIDTEMP
  369. for(uint_least8_t e = 0; e < EXTRUDERS; e++) {
  370. iState_sum_max[e] = PID_INTEGRAL_DRIVE_MAX / cs.Ki;
  371. }
  372. #endif
  373. #ifdef PIDTEMPBED
  374. temp_iState_max_bed = PID_INTEGRAL_DRIVE_MAX / cs.bedKi;
  375. #endif
  376. }
  377. int getHeaterPower(int heater) {
  378. if (heater<0)
  379. return soft_pwm_bed;
  380. return soft_pwm[heater];
  381. }
  382. // ready for eventually parameters adjusting
  383. void resetPID(uint8_t) // only for compiler-warning elimination (if function do nothing)
  384. //void resetPID(uint8_t extruder)
  385. {
  386. }
  387. void manage_heater()
  388. {
  389. #ifdef WATCHDOG
  390. wdt_reset();
  391. #endif //WATCHDOG
  392. float pid_input;
  393. float pid_output;
  394. // run at TEMP_MEAS_RATE
  395. if(temp_meas_ready != true) return;
  396. static unsigned long old_stamp = _millis();
  397. unsigned long new_stamp = _millis();
  398. unsigned long diff = new_stamp - old_stamp;
  399. if(diff < TEMP_MEAS_RATE) return;
  400. old_stamp = new_stamp;
  401. // ADC values need to be converted before checking: converted values are later used in MINTEMP
  402. updateTemperaturesFromRawValues();
  403. check_max_temp();
  404. check_min_temp();
  405. #ifdef TEMP_RUNAWAY_BED_HYSTERESIS
  406. temp_runaway_check(0, target_temperature_bed, current_temperature_bed, (int)soft_pwm_bed, true);
  407. #endif
  408. for(uint8_t e = 0; e < EXTRUDERS; e++)
  409. {
  410. #ifdef TEMP_RUNAWAY_EXTRUDER_HYSTERESIS
  411. temp_runaway_check(e+1, target_temperature[e], current_temperature[e], (int)soft_pwm[e], false);
  412. #endif
  413. #ifdef PIDTEMP
  414. pid_input = current_temperature[e];
  415. #ifndef PID_OPENLOOP
  416. if(target_temperature[e] == 0) {
  417. pid_output = 0;
  418. pid_reset[e] = true;
  419. } else {
  420. pid_error[e] = target_temperature[e] - pid_input;
  421. if(pid_reset[e]) {
  422. iState_sum[e] = 0.0;
  423. dTerm[e] = 0.0; // 'dState_last[e]' initial setting is not necessary (see end of if-statement)
  424. pid_reset[e] = false;
  425. }
  426. #ifndef PonM
  427. pTerm[e] = cs.Kp * pid_error[e];
  428. iState_sum[e] += pid_error[e];
  429. iState_sum[e] = constrain(iState_sum[e], iState_sum_min[e], iState_sum_max[e]);
  430. iTerm[e] = cs.Ki * iState_sum[e];
  431. // PID_K1 defined in Configuration.h in the PID settings
  432. #define K2 (1.0-PID_K1)
  433. dTerm[e] = (cs.Kd * (pid_input - dState_last[e]))*K2 + (PID_K1 * dTerm[e]); // e.g. digital filtration of derivative term changes
  434. 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)
  435. if (pid_output > PID_MAX) {
  436. if (pid_error[e] > 0 ) iState_sum[e] -= pid_error[e]; // conditional un-integration
  437. pid_output=PID_MAX;
  438. } else if (pid_output < 0) {
  439. if (pid_error[e] < 0 ) iState_sum[e] -= pid_error[e]; // conditional un-integration
  440. pid_output=0;
  441. }
  442. #else // PonM ("Proportional on Measurement" method)
  443. iState_sum[e] += cs.Ki * pid_error[e];
  444. iState_sum[e] -= cs.Kp * (pid_input - dState_last[e]);
  445. iState_sum[e] = constrain(iState_sum[e], 0, PID_INTEGRAL_DRIVE_MAX);
  446. dTerm[e] = cs.Kd * (pid_input - dState_last[e]);
  447. 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)
  448. pid_output = constrain(pid_output, 0, PID_MAX);
  449. #endif // PonM
  450. }
  451. dState_last[e] = pid_input;
  452. #else
  453. pid_output = constrain(target_temperature[e], 0, PID_MAX);
  454. #endif //PID_OPENLOOP
  455. #ifdef PID_DEBUG
  456. SERIAL_ECHO_START;
  457. SERIAL_ECHO(" PID_DEBUG ");
  458. SERIAL_ECHO(e);
  459. SERIAL_ECHO(": Input ");
  460. SERIAL_ECHO(pid_input);
  461. SERIAL_ECHO(" Output ");
  462. SERIAL_ECHO(pid_output);
  463. SERIAL_ECHO(" pTerm ");
  464. SERIAL_ECHO(pTerm[e]);
  465. SERIAL_ECHO(" iTerm ");
  466. SERIAL_ECHO(iTerm[e]);
  467. SERIAL_ECHO(" dTerm ");
  468. SERIAL_ECHOLN(-dTerm[e]);
  469. #endif //PID_DEBUG
  470. #else /* PID off */
  471. pid_output = 0;
  472. if(current_temperature[e] < target_temperature[e]) {
  473. pid_output = PID_MAX;
  474. }
  475. #endif
  476. // Check if temperature is within the correct range
  477. if((current_temperature[e] < maxttemp[e]) && (target_temperature[e] != 0))
  478. {
  479. soft_pwm[e] = (int)pid_output >> 1;
  480. }
  481. else
  482. {
  483. soft_pwm[e] = 0;
  484. }
  485. } // End extruder for loop
  486. checkFans();
  487. #ifndef PIDTEMPBED
  488. if(_millis() - previous_millis_bed_heater < BED_CHECK_INTERVAL)
  489. return;
  490. previous_millis_bed_heater = _millis();
  491. #endif
  492. #if TEMP_SENSOR_BED != 0
  493. #ifdef PIDTEMPBED
  494. pid_input = current_temperature_bed;
  495. #ifndef PID_OPENLOOP
  496. pid_error_bed = target_temperature_bed - pid_input;
  497. pTerm_bed = cs.bedKp * pid_error_bed;
  498. temp_iState_bed += pid_error_bed;
  499. temp_iState_bed = constrain(temp_iState_bed, temp_iState_min_bed, temp_iState_max_bed);
  500. iTerm_bed = cs.bedKi * temp_iState_bed;
  501. //PID_K1 defined in Configuration.h in the PID settings
  502. #define K2 (1.0-PID_K1)
  503. dTerm_bed= (cs.bedKd * (pid_input - temp_dState_bed))*K2 + (PID_K1 * dTerm_bed);
  504. temp_dState_bed = pid_input;
  505. pid_output = pTerm_bed + iTerm_bed - dTerm_bed;
  506. if (pid_output > MAX_BED_POWER) {
  507. if (pid_error_bed > 0 ) temp_iState_bed -= pid_error_bed; // conditional un-integration
  508. pid_output=MAX_BED_POWER;
  509. } else if (pid_output < 0){
  510. if (pid_error_bed < 0 ) temp_iState_bed -= pid_error_bed; // conditional un-integration
  511. pid_output=0;
  512. }
  513. #else
  514. pid_output = constrain(target_temperature_bed, 0, MAX_BED_POWER);
  515. #endif //PID_OPENLOOP
  516. if(current_temperature_bed < BED_MAXTEMP)
  517. {
  518. soft_pwm_bed = (int)pid_output >> 1;
  519. timer02_set_pwm0(soft_pwm_bed << 1);
  520. }
  521. else {
  522. soft_pwm_bed = 0;
  523. timer02_set_pwm0(soft_pwm_bed << 1);
  524. }
  525. #elif !defined(BED_LIMIT_SWITCHING)
  526. // Check if temperature is within the correct range
  527. if(current_temperature_bed < BED_MAXTEMP)
  528. {
  529. if(current_temperature_bed >= target_temperature_bed)
  530. {
  531. soft_pwm_bed = 0;
  532. timer02_set_pwm0(soft_pwm_bed << 1);
  533. }
  534. else
  535. {
  536. soft_pwm_bed = MAX_BED_POWER>>1;
  537. timer02_set_pwm0(soft_pwm_bed << 1);
  538. }
  539. }
  540. else
  541. {
  542. soft_pwm_bed = 0;
  543. timer02_set_pwm0(soft_pwm_bed << 1);
  544. WRITE(HEATER_BED_PIN,LOW);
  545. }
  546. #else //#ifdef BED_LIMIT_SWITCHING
  547. // Check if temperature is within the correct band
  548. if(current_temperature_bed < BED_MAXTEMP)
  549. {
  550. if(current_temperature_bed > target_temperature_bed + BED_HYSTERESIS)
  551. {
  552. soft_pwm_bed = 0;
  553. timer02_set_pwm0(soft_pwm_bed << 1);
  554. }
  555. else if(current_temperature_bed <= target_temperature_bed - BED_HYSTERESIS)
  556. {
  557. soft_pwm_bed = MAX_BED_POWER>>1;
  558. timer02_set_pwm0(soft_pwm_bed << 1);
  559. }
  560. }
  561. else
  562. {
  563. soft_pwm_bed = 0;
  564. timer02_set_pwm0(soft_pwm_bed << 1);
  565. WRITE(HEATER_BED_PIN,LOW);
  566. }
  567. #endif
  568. if(target_temperature_bed==0)
  569. {
  570. soft_pwm_bed = 0;
  571. timer02_set_pwm0(soft_pwm_bed << 1);
  572. }
  573. #endif
  574. }
  575. #define PGM_RD_W(x) (short)pgm_read_word(&x)
  576. // Derived from RepRap FiveD extruder::getTemperature()
  577. // For hot end temperature measurement.
  578. static float analog2temp(int raw, uint8_t e) {
  579. if(e >= EXTRUDERS)
  580. {
  581. SERIAL_ERROR_START;
  582. SERIAL_ERROR((int)e);
  583. SERIAL_ERRORLNPGM(" - Invalid extruder number !");
  584. kill(NULL, 6);
  585. return 0.0;
  586. }
  587. #ifdef HEATER_0_USES_MAX6675
  588. if (e == 0)
  589. {
  590. return 0.25 * raw;
  591. }
  592. #endif
  593. if(heater_ttbl_map[e] != NULL)
  594. {
  595. float celsius = 0;
  596. uint8_t i;
  597. short (*tt)[][2] = (short (*)[][2])(heater_ttbl_map[e]);
  598. for (i=1; i<heater_ttbllen_map[e]; i++)
  599. {
  600. if (PGM_RD_W((*tt)[i][0]) > raw)
  601. {
  602. celsius = PGM_RD_W((*tt)[i-1][1]) +
  603. (raw - PGM_RD_W((*tt)[i-1][0])) *
  604. (float)(PGM_RD_W((*tt)[i][1]) - PGM_RD_W((*tt)[i-1][1])) /
  605. (float)(PGM_RD_W((*tt)[i][0]) - PGM_RD_W((*tt)[i-1][0]));
  606. break;
  607. }
  608. }
  609. // Overflow: Set to last value in the table
  610. if (i == heater_ttbllen_map[e]) celsius = PGM_RD_W((*tt)[i-1][1]);
  611. return celsius;
  612. }
  613. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET;
  614. }
  615. // Derived from RepRap FiveD extruder::getTemperature()
  616. // For bed temperature measurement.
  617. static float analog2tempBed(int raw) {
  618. #ifdef BED_USES_THERMISTOR
  619. float celsius = 0;
  620. byte i;
  621. for (i=1; i<BEDTEMPTABLE_LEN; i++)
  622. {
  623. if (PGM_RD_W(BEDTEMPTABLE[i][0]) > raw)
  624. {
  625. celsius = PGM_RD_W(BEDTEMPTABLE[i-1][1]) +
  626. (raw - PGM_RD_W(BEDTEMPTABLE[i-1][0])) *
  627. (float)(PGM_RD_W(BEDTEMPTABLE[i][1]) - PGM_RD_W(BEDTEMPTABLE[i-1][1])) /
  628. (float)(PGM_RD_W(BEDTEMPTABLE[i][0]) - PGM_RD_W(BEDTEMPTABLE[i-1][0]));
  629. break;
  630. }
  631. }
  632. // Overflow: Set to last value in the table
  633. if (i == BEDTEMPTABLE_LEN) celsius = PGM_RD_W(BEDTEMPTABLE[i-1][1]);
  634. // temperature offset adjustment
  635. #ifdef BED_OFFSET
  636. float _offset = BED_OFFSET;
  637. float _offset_center = BED_OFFSET_CENTER;
  638. float _offset_start = BED_OFFSET_START;
  639. float _first_koef = (_offset / 2) / (_offset_center - _offset_start);
  640. float _second_koef = (_offset / 2) / (100 - _offset_center);
  641. if (celsius >= _offset_start && celsius <= _offset_center)
  642. {
  643. celsius = celsius + (_first_koef * (celsius - _offset_start));
  644. }
  645. else if (celsius > _offset_center && celsius <= 100)
  646. {
  647. celsius = celsius + (_first_koef * (_offset_center - _offset_start)) + ( _second_koef * ( celsius - ( 100 - _offset_center ) )) ;
  648. }
  649. else if (celsius > 100)
  650. {
  651. celsius = celsius + _offset;
  652. }
  653. #endif
  654. return celsius;
  655. #elif defined BED_USES_AD595
  656. return ((raw * ((5.0 * 100.0) / 1024.0) / OVERSAMPLENR) * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET;
  657. #else
  658. return 0;
  659. #endif
  660. }
  661. #ifdef AMBIENT_THERMISTOR
  662. static float analog2tempAmbient(int raw)
  663. {
  664. float celsius = 0;
  665. byte i;
  666. for (i=1; i<AMBIENTTEMPTABLE_LEN; i++)
  667. {
  668. if (PGM_RD_W(AMBIENTTEMPTABLE[i][0]) > raw)
  669. {
  670. celsius = PGM_RD_W(AMBIENTTEMPTABLE[i-1][1]) +
  671. (raw - PGM_RD_W(AMBIENTTEMPTABLE[i-1][0])) *
  672. (float)(PGM_RD_W(AMBIENTTEMPTABLE[i][1]) - PGM_RD_W(AMBIENTTEMPTABLE[i-1][1])) /
  673. (float)(PGM_RD_W(AMBIENTTEMPTABLE[i][0]) - PGM_RD_W(AMBIENTTEMPTABLE[i-1][0]));
  674. break;
  675. }
  676. }
  677. // Overflow: Set to last value in the table
  678. if (i == AMBIENTTEMPTABLE_LEN) celsius = PGM_RD_W(AMBIENTTEMPTABLE[i-1][1]);
  679. return celsius;
  680. }
  681. #endif //AMBIENT_THERMISTOR
  682. /* Called to get the raw values into the the actual temperatures. The raw values are created in interrupt context,
  683. and this function is called from normal context as it is too slow to run in interrupts and will block the stepper routine otherwise */
  684. static void updateTemperaturesFromRawValues()
  685. {
  686. CRITICAL_SECTION_START;
  687. adc_start_cycle();
  688. temp_meas_ready = false;
  689. CRITICAL_SECTION_END;
  690. for(uint8_t e=0;e<EXTRUDERS;e++)
  691. {
  692. current_temperature[e] = analog2temp(current_temperature_raw[e], e);
  693. }
  694. #ifdef PINDA_THERMISTOR
  695. current_temperature_raw_pinda = (uint16_t)((uint32_t)current_temperature_raw_pinda * 3 + current_temperature_raw_pinda_fast) >> 2;
  696. current_temperature_pinda = analog2tempBed(current_temperature_raw_pinda);
  697. #endif
  698. #ifdef AMBIENT_THERMISTOR
  699. current_temperature_ambient = analog2tempAmbient(current_temperature_raw_ambient); //thermistor for ambient is NTCG104LH104JT1 (2000)
  700. #endif
  701. #ifdef DEBUG_HEATER_BED_SIM
  702. current_temperature_bed = target_temperature_bed;
  703. #else //DEBUG_HEATER_BED_SIM
  704. current_temperature_bed = analog2tempBed(current_temperature_bed_raw);
  705. #endif //DEBUG_HEATER_BED_SIM
  706. }
  707. void tp_init()
  708. {
  709. #if MB(RUMBA) && ((TEMP_SENSOR_0==-1)||(TEMP_SENSOR_1==-1)||(TEMP_SENSOR_2==-1)||(TEMP_SENSOR_BED==-1))
  710. //disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector
  711. MCUCR=(1<<JTD);
  712. MCUCR=(1<<JTD);
  713. #endif
  714. // Finish init of mult extruder arrays
  715. for(int e = 0; e < EXTRUDERS; e++) {
  716. // populate with the first value
  717. maxttemp[e] = maxttemp[0];
  718. #ifdef PIDTEMP
  719. iState_sum_min[e] = 0.0;
  720. iState_sum_max[e] = PID_INTEGRAL_DRIVE_MAX / cs.Ki;
  721. #endif //PIDTEMP
  722. #ifdef PIDTEMPBED
  723. temp_iState_min_bed = 0.0;
  724. temp_iState_max_bed = PID_INTEGRAL_DRIVE_MAX / cs.bedKi;
  725. #endif //PIDTEMPBED
  726. }
  727. #if defined(HEATER_0_PIN) && (HEATER_0_PIN > -1)
  728. SET_OUTPUT(HEATER_0_PIN);
  729. #endif
  730. #if defined(HEATER_1_PIN) && (HEATER_1_PIN > -1)
  731. SET_OUTPUT(HEATER_1_PIN);
  732. #endif
  733. #if defined(HEATER_2_PIN) && (HEATER_2_PIN > -1)
  734. SET_OUTPUT(HEATER_2_PIN);
  735. #endif
  736. #if defined(HEATER_BED_PIN) && (HEATER_BED_PIN > -1)
  737. SET_OUTPUT(HEATER_BED_PIN);
  738. #endif
  739. #if defined(FAN_PIN) && (FAN_PIN > -1)
  740. SET_OUTPUT(FAN_PIN);
  741. #ifdef FAST_PWM_FAN
  742. setPwmFrequency(FAN_PIN, 1); // No prescaling. Pwm frequency = F_CPU/256/8
  743. #endif
  744. #ifdef FAN_SOFT_PWM
  745. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  746. #endif
  747. #endif
  748. #ifdef HEATER_0_USES_MAX6675
  749. #ifndef SDSUPPORT
  750. SET_OUTPUT(SCK_PIN);
  751. WRITE(SCK_PIN,0);
  752. SET_OUTPUT(MOSI_PIN);
  753. WRITE(MOSI_PIN,1);
  754. SET_INPUT(MISO_PIN);
  755. WRITE(MISO_PIN,1);
  756. #endif
  757. /* Using pinMode and digitalWrite, as that was the only way I could get it to compile */
  758. //Have to toggle SD card CS pin to low first, to enable firmware to talk with SD card
  759. pinMode(SS_PIN, OUTPUT);
  760. digitalWrite(SS_PIN,0);
  761. pinMode(MAX6675_SS, OUTPUT);
  762. digitalWrite(MAX6675_SS,1);
  763. #endif
  764. // initialize the ADC and start a conversion
  765. adc_init();
  766. adc_start_cycle();
  767. timer0_init(); //enables the heatbed timer.
  768. // timer2 already enabled earlier in the code
  769. // now enable the COMPB temperature interrupt
  770. OCR2B = 128;
  771. ENABLE_SOFT_PWM_INTERRUPT();
  772. timer4_init(); //for tone and Extruder fan PWM
  773. // Wait for temperature measurement to settle
  774. _delay(250);
  775. #ifdef HEATER_0_MINTEMP
  776. minttemp[0] = HEATER_0_MINTEMP;
  777. while(analog2temp(minttemp_raw[0], 0) < HEATER_0_MINTEMP) {
  778. #if HEATER_0_RAW_LO_TEMP < HEATER_0_RAW_HI_TEMP
  779. minttemp_raw[0] += OVERSAMPLENR;
  780. #else
  781. minttemp_raw[0] -= OVERSAMPLENR;
  782. #endif
  783. }
  784. #endif //MINTEMP
  785. #ifdef HEATER_0_MAXTEMP
  786. maxttemp[0] = HEATER_0_MAXTEMP;
  787. while(analog2temp(maxttemp_raw[0], 0) > HEATER_0_MAXTEMP) {
  788. #if HEATER_0_RAW_LO_TEMP < HEATER_0_RAW_HI_TEMP
  789. maxttemp_raw[0] -= OVERSAMPLENR;
  790. #else
  791. maxttemp_raw[0] += OVERSAMPLENR;
  792. #endif
  793. }
  794. #endif //MAXTEMP
  795. #if (EXTRUDERS > 1) && defined(HEATER_1_MINTEMP)
  796. minttemp[1] = HEATER_1_MINTEMP;
  797. while(analog2temp(minttemp_raw[1], 1) < HEATER_1_MINTEMP) {
  798. #if HEATER_1_RAW_LO_TEMP < HEATER_1_RAW_HI_TEMP
  799. minttemp_raw[1] += OVERSAMPLENR;
  800. #else
  801. minttemp_raw[1] -= OVERSAMPLENR;
  802. #endif
  803. }
  804. #endif // MINTEMP 1
  805. #if (EXTRUDERS > 1) && defined(HEATER_1_MAXTEMP)
  806. maxttemp[1] = HEATER_1_MAXTEMP;
  807. while(analog2temp(maxttemp_raw[1], 1) > HEATER_1_MAXTEMP) {
  808. #if HEATER_1_RAW_LO_TEMP < HEATER_1_RAW_HI_TEMP
  809. maxttemp_raw[1] -= OVERSAMPLENR;
  810. #else
  811. maxttemp_raw[1] += OVERSAMPLENR;
  812. #endif
  813. }
  814. #endif //MAXTEMP 1
  815. #if (EXTRUDERS > 2) && defined(HEATER_2_MINTEMP)
  816. minttemp[2] = HEATER_2_MINTEMP;
  817. while(analog2temp(minttemp_raw[2], 2) < HEATER_2_MINTEMP) {
  818. #if HEATER_2_RAW_LO_TEMP < HEATER_2_RAW_HI_TEMP
  819. minttemp_raw[2] += OVERSAMPLENR;
  820. #else
  821. minttemp_raw[2] -= OVERSAMPLENR;
  822. #endif
  823. }
  824. #endif //MINTEMP 2
  825. #if (EXTRUDERS > 2) && defined(HEATER_2_MAXTEMP)
  826. maxttemp[2] = HEATER_2_MAXTEMP;
  827. while(analog2temp(maxttemp_raw[2], 2) > HEATER_2_MAXTEMP) {
  828. #if HEATER_2_RAW_LO_TEMP < HEATER_2_RAW_HI_TEMP
  829. maxttemp_raw[2] -= OVERSAMPLENR;
  830. #else
  831. maxttemp_raw[2] += OVERSAMPLENR;
  832. #endif
  833. }
  834. #endif //MAXTEMP 2
  835. #ifdef BED_MINTEMP
  836. while(analog2tempBed(bed_minttemp_raw) < BED_MINTEMP) {
  837. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  838. bed_minttemp_raw += OVERSAMPLENR;
  839. #else
  840. bed_minttemp_raw -= OVERSAMPLENR;
  841. #endif
  842. }
  843. #endif //BED_MINTEMP
  844. #ifdef BED_MAXTEMP
  845. while(analog2tempBed(bed_maxttemp_raw) > BED_MAXTEMP) {
  846. #if HEATER_BED_RAW_LO_TEMP < HEATER_BED_RAW_HI_TEMP
  847. bed_maxttemp_raw -= OVERSAMPLENR;
  848. #else
  849. bed_maxttemp_raw += OVERSAMPLENR;
  850. #endif
  851. }
  852. #endif //BED_MAXTEMP
  853. #ifdef AMBIENT_MINTEMP
  854. while(analog2tempAmbient(ambient_minttemp_raw) < AMBIENT_MINTEMP) {
  855. #if AMBIENT_RAW_LO_TEMP < AMBIENT_RAW_HI_TEMP
  856. ambient_minttemp_raw += OVERSAMPLENR;
  857. #else
  858. ambient_minttemp_raw -= OVERSAMPLENR;
  859. #endif
  860. }
  861. #endif //AMBIENT_MINTEMP
  862. #ifdef AMBIENT_MAXTEMP
  863. while(analog2tempAmbient(ambient_maxttemp_raw) > AMBIENT_MAXTEMP) {
  864. #if AMBIENT_RAW_LO_TEMP < AMBIENT_RAW_HI_TEMP
  865. ambient_maxttemp_raw -= OVERSAMPLENR;
  866. #else
  867. ambient_maxttemp_raw += OVERSAMPLENR;
  868. #endif
  869. }
  870. #endif //AMBIENT_MAXTEMP
  871. }
  872. #if (defined (TEMP_RUNAWAY_BED_HYSTERESIS) && TEMP_RUNAWAY_BED_TIMEOUT > 0) || (defined (TEMP_RUNAWAY_EXTRUDER_HYSTERESIS) && TEMP_RUNAWAY_EXTRUDER_TIMEOUT > 0)
  873. void temp_runaway_check(uint8_t _heater_id, float _target_temperature, float _current_temperature, float _output, bool _isbed)
  874. {
  875. float __delta;
  876. float __hysteresis = 0;
  877. uint16_t __timeout = 0;
  878. bool temp_runaway_check_active = false;
  879. static float __preheat_start[2] = { 0,0}; //currently just bed and one extruder
  880. static uint8_t __preheat_counter[2] = { 0,0};
  881. static uint8_t __preheat_errors[2] = { 0,0};
  882. if (_millis() - temp_runaway_timer[_heater_id] > 2000)
  883. {
  884. #ifdef TEMP_RUNAWAY_BED_TIMEOUT
  885. if (_isbed)
  886. {
  887. __hysteresis = TEMP_RUNAWAY_BED_HYSTERESIS;
  888. __timeout = TEMP_RUNAWAY_BED_TIMEOUT;
  889. }
  890. #endif
  891. #ifdef TEMP_RUNAWAY_EXTRUDER_TIMEOUT
  892. if (!_isbed)
  893. {
  894. __hysteresis = TEMP_RUNAWAY_EXTRUDER_HYSTERESIS;
  895. __timeout = TEMP_RUNAWAY_EXTRUDER_TIMEOUT;
  896. }
  897. #endif
  898. temp_runaway_timer[_heater_id] = _millis();
  899. if (_output == 0)
  900. {
  901. temp_runaway_check_active = false;
  902. temp_runaway_error_counter[_heater_id] = 0;
  903. }
  904. if (temp_runaway_target[_heater_id] != _target_temperature)
  905. {
  906. if (_target_temperature > 0)
  907. {
  908. temp_runaway_status[_heater_id] = TempRunaway_PREHEAT;
  909. temp_runaway_target[_heater_id] = _target_temperature;
  910. __preheat_start[_heater_id] = _current_temperature;
  911. __preheat_counter[_heater_id] = 0;
  912. }
  913. else
  914. {
  915. temp_runaway_status[_heater_id] = TempRunaway_INACTIVE;
  916. temp_runaway_target[_heater_id] = _target_temperature;
  917. }
  918. }
  919. if ((_current_temperature < _target_temperature) && (temp_runaway_status[_heater_id] == TempRunaway_PREHEAT))
  920. {
  921. __preheat_counter[_heater_id]++;
  922. if (__preheat_counter[_heater_id] > ((_isbed) ? 16 : 8)) // periodicaly check if current temperature changes
  923. {
  924. /*SERIAL_ECHOPGM("Heater:");
  925. MYSERIAL.print(_heater_id);
  926. SERIAL_ECHOPGM(" T:");
  927. MYSERIAL.print(_current_temperature);
  928. SERIAL_ECHOPGM(" Tstart:");
  929. MYSERIAL.print(__preheat_start[_heater_id]);
  930. SERIAL_ECHOPGM(" delta:");
  931. MYSERIAL.print(_current_temperature-__preheat_start[_heater_id]);*/
  932. //-// if (_current_temperature - __preheat_start[_heater_id] < 2) {
  933. //-// if (_current_temperature - __preheat_start[_heater_id] < ((_isbed && (_current_temperature>105.0))?0.6:2.0)) {
  934. __delta=2.0;
  935. if(_isbed)
  936. {
  937. __delta=3.0;
  938. if(_current_temperature>90.0) __delta=2.0;
  939. if(_current_temperature>105.0) __delta=0.6;
  940. }
  941. if (_current_temperature - __preheat_start[_heater_id] < __delta) {
  942. __preheat_errors[_heater_id]++;
  943. /*SERIAL_ECHOPGM(" Preheat errors:");
  944. MYSERIAL.println(__preheat_errors[_heater_id]);*/
  945. }
  946. else {
  947. //SERIAL_ECHOLNPGM("");
  948. __preheat_errors[_heater_id] = 0;
  949. }
  950. if (__preheat_errors[_heater_id] > ((_isbed) ? 3 : 5))
  951. {
  952. if (farm_mode) { prusa_statistics(0); }
  953. temp_runaway_stop(true, _isbed);
  954. if (farm_mode) { prusa_statistics(91); }
  955. }
  956. __preheat_start[_heater_id] = _current_temperature;
  957. __preheat_counter[_heater_id] = 0;
  958. }
  959. }
  960. //-// if (_current_temperature >= _target_temperature && temp_runaway_status[_heater_id] == TempRunaway_PREHEAT)
  961. if ((_current_temperature > (_target_temperature - __hysteresis)) && temp_runaway_status[_heater_id] == TempRunaway_PREHEAT)
  962. {
  963. /*SERIAL_ECHOPGM("Heater:");
  964. MYSERIAL.print(_heater_id);
  965. MYSERIAL.println(" ->tempRunaway");*/
  966. temp_runaway_status[_heater_id] = TempRunaway_ACTIVE;
  967. temp_runaway_check_active = false;
  968. temp_runaway_error_counter[_heater_id] = 0;
  969. }
  970. if (_output > 0)
  971. {
  972. temp_runaway_check_active = true;
  973. }
  974. if (temp_runaway_check_active)
  975. {
  976. // we are in range
  977. if ((_current_temperature > (_target_temperature - __hysteresis)) && (_current_temperature < (_target_temperature + __hysteresis)))
  978. {
  979. temp_runaway_check_active = false;
  980. temp_runaway_error_counter[_heater_id] = 0;
  981. }
  982. else
  983. {
  984. if (temp_runaway_status[_heater_id] > TempRunaway_PREHEAT)
  985. {
  986. temp_runaway_error_counter[_heater_id]++;
  987. if (temp_runaway_error_counter[_heater_id] * 2 > __timeout)
  988. {
  989. if (farm_mode) { prusa_statistics(0); }
  990. temp_runaway_stop(false, _isbed);
  991. if (farm_mode) { prusa_statistics(90); }
  992. }
  993. }
  994. }
  995. }
  996. }
  997. }
  998. void temp_runaway_stop(bool isPreheat, bool isBed)
  999. {
  1000. disable_heater();
  1001. Sound_MakeCustom(200,0,true);
  1002. if (isPreheat)
  1003. {
  1004. lcd_setalertstatuspgm(isBed? PSTR("BED PREHEAT ERROR") : PSTR("PREHEAT ERROR"), LCD_STATUS_CRITICAL);
  1005. SERIAL_ERROR_START;
  1006. isBed ? SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HEATBED)") : SERIAL_ERRORLNPGM(" THERMAL RUNAWAY (PREHEAT HOTEND)");
  1007. hotendFanSetFullSpeed();
  1008. }
  1009. else
  1010. {
  1011. lcd_setalertstatuspgm(isBed? PSTR("BED THERMAL RUNAWAY") : PSTR("THERMAL RUNAWAY"), LCD_STATUS_CRITICAL);
  1012. SERIAL_ERROR_START;
  1013. isBed ? SERIAL_ERRORLNPGM(" HEATBED THERMAL RUNAWAY") : SERIAL_ERRORLNPGM(" HOTEND THERMAL RUNAWAY");
  1014. }
  1015. Stop();
  1016. }
  1017. #endif
  1018. void disable_heater()
  1019. {
  1020. setAllTargetHotends(0);
  1021. setTargetBed(0);
  1022. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  1023. target_temperature[0]=0;
  1024. soft_pwm[0]=0;
  1025. #if defined(HEATER_0_PIN) && HEATER_0_PIN > -1
  1026. WRITE(HEATER_0_PIN,LOW);
  1027. #endif
  1028. #endif
  1029. #if defined(TEMP_1_PIN) && TEMP_1_PIN > -1 && EXTRUDERS > 1
  1030. target_temperature[1]=0;
  1031. soft_pwm[1]=0;
  1032. #if defined(HEATER_1_PIN) && HEATER_1_PIN > -1
  1033. WRITE(HEATER_1_PIN,LOW);
  1034. #endif
  1035. #endif
  1036. #if defined(TEMP_2_PIN) && TEMP_2_PIN > -1 && EXTRUDERS > 2
  1037. target_temperature[2]=0;
  1038. soft_pwm[2]=0;
  1039. #if defined(HEATER_2_PIN) && HEATER_2_PIN > -1
  1040. WRITE(HEATER_2_PIN,LOW);
  1041. #endif
  1042. #endif
  1043. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  1044. target_temperature_bed=0;
  1045. soft_pwm_bed=0;
  1046. timer02_set_pwm0(soft_pwm_bed << 1);
  1047. bedPWMDisabled = 0;
  1048. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1049. //WRITE(HEATER_BED_PIN,LOW);
  1050. #endif
  1051. #endif
  1052. }
  1053. //! codes of alert messages for the LCD - it is shorter to compare an uin8_t
  1054. //! than raw const char * of the messages themselves.
  1055. //! Could be used for MAXTEMP situations too - after reaching MAXTEMP and turning off the heater automagically
  1056. //! the heater/bed may cool down and a similar alert message like "MAXTERM fixed..." may be displayed.
  1057. enum { LCDALERT_NONE = 0, LCDALERT_HEATERMINTEMP, LCDALERT_BEDMINTEMP, LCDALERT_MINTEMPFIXED, LCDALERT_PLEASERESTART };
  1058. //! remember the last alert message sent to the LCD
  1059. //! to prevent flicker and improve speed
  1060. uint8_t last_alert_sent_to_lcd = LCDALERT_NONE;
  1061. //! update the current temperature error message
  1062. //! @param type short error abbreviation (PROGMEM)
  1063. void temp_update_messagepgm(const char* PROGMEM type)
  1064. {
  1065. char msg[LCD_WIDTH];
  1066. strcpy_P(msg, PSTR("Err: "));
  1067. strcat_P(msg, type);
  1068. lcd_setalertstatus(msg, LCD_STATUS_CRITICAL);
  1069. }
  1070. //! signal a temperature error on both the lcd and serial
  1071. //! @param type short error abbreviation (PROGMEM)
  1072. //! @param e optional extruder index for hotend errors
  1073. void temp_error_messagepgm(const char* PROGMEM type, uint8_t e = EXTRUDERS)
  1074. {
  1075. temp_update_messagepgm(type);
  1076. SERIAL_ERROR_START;
  1077. if(e != EXTRUDERS) {
  1078. SERIAL_ERROR((int)e);
  1079. SERIAL_ERRORPGM(": ");
  1080. }
  1081. SERIAL_ERRORPGM("Heaters switched off. ");
  1082. SERIAL_ERRORRPGM(type);
  1083. SERIAL_ERRORLNPGM(" triggered!");
  1084. }
  1085. void max_temp_error(uint8_t e) {
  1086. disable_heater();
  1087. if(IsStopped() == false) {
  1088. temp_error_messagepgm(PSTR("MAXTEMP"), e);
  1089. }
  1090. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  1091. Stop();
  1092. #endif
  1093. hotendFanSetFullSpeed();
  1094. if (farm_mode) { prusa_statistics(93); }
  1095. }
  1096. void min_temp_error(uint8_t e) {
  1097. #ifdef DEBUG_DISABLE_MINTEMP
  1098. return;
  1099. #endif
  1100. disable_heater();
  1101. //if (current_temperature_ambient < MINTEMP_MINAMBIENT) return;
  1102. static const char err[] PROGMEM = "MINTEMP";
  1103. if(IsStopped() == false) {
  1104. temp_error_messagepgm(err, e);
  1105. last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  1106. } else if( last_alert_sent_to_lcd != LCDALERT_HEATERMINTEMP ){ // only update, if the lcd message is to be changed (i.e. not the same as last time)
  1107. // we are already stopped due to some error, only update the status message without flickering
  1108. temp_update_messagepgm(err);
  1109. last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  1110. }
  1111. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  1112. // if( last_alert_sent_to_lcd != LCDALERT_HEATERMINTEMP ){
  1113. // last_alert_sent_to_lcd = LCDALERT_HEATERMINTEMP;
  1114. // lcd_print_stop();
  1115. // }
  1116. Stop();
  1117. #endif
  1118. if (farm_mode) { prusa_statistics(92); }
  1119. }
  1120. void bed_max_temp_error(void) {
  1121. disable_heater();
  1122. if(IsStopped() == false) {
  1123. temp_error_messagepgm(PSTR("MAXTEMP BED"));
  1124. }
  1125. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  1126. Stop();
  1127. #endif
  1128. }
  1129. void bed_min_temp_error(void) {
  1130. #ifdef DEBUG_DISABLE_MINTEMP
  1131. return;
  1132. #endif
  1133. disable_heater();
  1134. static const char err[] PROGMEM = "MINTEMP BED";
  1135. if(IsStopped() == false) {
  1136. temp_error_messagepgm(err);
  1137. last_alert_sent_to_lcd = LCDALERT_BEDMINTEMP;
  1138. } else if( last_alert_sent_to_lcd != LCDALERT_BEDMINTEMP ){ // only update, if the lcd message is to be changed (i.e. not the same as last time)
  1139. // we are already stopped due to some error, only update the status message without flickering
  1140. temp_update_messagepgm(err);
  1141. last_alert_sent_to_lcd = LCDALERT_BEDMINTEMP;
  1142. }
  1143. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  1144. Stop();
  1145. #endif
  1146. }
  1147. #ifdef AMBIENT_THERMISTOR
  1148. void ambient_max_temp_error(void) {
  1149. disable_heater();
  1150. if(IsStopped() == false) {
  1151. temp_error_messagepgm(PSTR("MAXTEMP AMB"));
  1152. }
  1153. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  1154. Stop();
  1155. #endif
  1156. }
  1157. void ambient_min_temp_error(void) {
  1158. #ifdef DEBUG_DISABLE_MINTEMP
  1159. return;
  1160. #endif
  1161. disable_heater();
  1162. if(IsStopped() == false) {
  1163. temp_error_messagepgm(PSTR("MINTEMP AMB"));
  1164. }
  1165. #ifndef BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
  1166. Stop();
  1167. #endif
  1168. }
  1169. #endif
  1170. #ifdef HEATER_0_USES_MAX6675
  1171. #define MAX6675_HEAT_INTERVAL 250
  1172. long max6675_previous_millis = MAX6675_HEAT_INTERVAL;
  1173. int max6675_temp = 2000;
  1174. int read_max6675()
  1175. {
  1176. if (_millis() - max6675_previous_millis < MAX6675_HEAT_INTERVAL)
  1177. return max6675_temp;
  1178. max6675_previous_millis = _millis();
  1179. max6675_temp = 0;
  1180. #ifdef PRR
  1181. PRR &= ~(1<<PRSPI);
  1182. #elif defined PRR0
  1183. PRR0 &= ~(1<<PRSPI);
  1184. #endif
  1185. SPCR = (1<<MSTR) | (1<<SPE) | (1<<SPR0);
  1186. // enable TT_MAX6675
  1187. WRITE(MAX6675_SS, 0);
  1188. // ensure 100ns delay - a bit extra is fine
  1189. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1190. asm("nop");//50ns on 20Mhz, 62.5ns on 16Mhz
  1191. // read MSB
  1192. SPDR = 0;
  1193. for (;(SPSR & (1<<SPIF)) == 0;);
  1194. max6675_temp = SPDR;
  1195. max6675_temp <<= 8;
  1196. // read LSB
  1197. SPDR = 0;
  1198. for (;(SPSR & (1<<SPIF)) == 0;);
  1199. max6675_temp |= SPDR;
  1200. // disable TT_MAX6675
  1201. WRITE(MAX6675_SS, 1);
  1202. if (max6675_temp & 4)
  1203. {
  1204. // thermocouple open
  1205. max6675_temp = 2000;
  1206. }
  1207. else
  1208. {
  1209. max6675_temp = max6675_temp >> 3;
  1210. }
  1211. return max6675_temp;
  1212. }
  1213. #endif
  1214. void adc_ready(void) //callback from adc when sampling finished
  1215. {
  1216. current_temperature_raw[0] = adc_values[ADC_PIN_IDX(TEMP_0_PIN)]; //heater
  1217. #ifdef PINDA_THERMISTOR
  1218. current_temperature_raw_pinda_fast = adc_values[ADC_PIN_IDX(TEMP_PINDA_PIN)];
  1219. #endif //PINDA_THERMISTOR
  1220. current_temperature_bed_raw = adc_values[ADC_PIN_IDX(TEMP_BED_PIN)];
  1221. #ifdef VOLT_PWR_PIN
  1222. current_voltage_raw_pwr = adc_values[ADC_PIN_IDX(VOLT_PWR_PIN)];
  1223. #endif
  1224. #ifdef AMBIENT_THERMISTOR
  1225. current_temperature_raw_ambient = adc_values[ADC_PIN_IDX(TEMP_AMBIENT_PIN)]; // 5->6
  1226. #endif //AMBIENT_THERMISTOR
  1227. #ifdef VOLT_BED_PIN
  1228. current_voltage_raw_bed = adc_values[ADC_PIN_IDX(VOLT_BED_PIN)]; // 6->9
  1229. #endif
  1230. #ifdef IR_SENSOR_ANALOG
  1231. current_voltage_raw_IR = adc_values[ADC_PIN_IDX(VOLT_IR_PIN)];
  1232. #endif //IR_SENSOR_ANALOG
  1233. temp_meas_ready = true;
  1234. }
  1235. #ifdef BABYSTEPPING
  1236. FORCE_INLINE static void applyBabysteps() {
  1237. for(uint8_t axis=0;axis<3;axis++)
  1238. {
  1239. int curTodo=babystepsTodo[axis]; //get rid of volatile for performance
  1240. if(curTodo>0)
  1241. {
  1242. CRITICAL_SECTION_START;
  1243. babystep(axis,/*fwd*/true);
  1244. babystepsTodo[axis]--; //less to do next time
  1245. CRITICAL_SECTION_END;
  1246. }
  1247. else
  1248. if(curTodo<0)
  1249. {
  1250. CRITICAL_SECTION_START;
  1251. babystep(axis,/*fwd*/false);
  1252. babystepsTodo[axis]++; //less to do next time
  1253. CRITICAL_SECTION_END;
  1254. }
  1255. }
  1256. }
  1257. #endif //BABYSTEPPING
  1258. FORCE_INLINE static void soft_pwm_isr()
  1259. {
  1260. lcd_buttons_update();
  1261. static uint8_t pwm_count = (1 << SOFT_PWM_SCALE);
  1262. static uint8_t soft_pwm_0;
  1263. #ifdef SLOW_PWM_HEATERS
  1264. static unsigned char slow_pwm_count = 0;
  1265. static unsigned char state_heater_0 = 0;
  1266. static unsigned char state_timer_heater_0 = 0;
  1267. #endif
  1268. #if (EXTRUDERS > 1) || defined(HEATERS_PARALLEL)
  1269. static unsigned char soft_pwm_1;
  1270. #ifdef SLOW_PWM_HEATERS
  1271. static unsigned char state_heater_1 = 0;
  1272. static unsigned char state_timer_heater_1 = 0;
  1273. #endif
  1274. #endif
  1275. #if EXTRUDERS > 2
  1276. static unsigned char soft_pwm_2;
  1277. #ifdef SLOW_PWM_HEATERS
  1278. static unsigned char state_heater_2 = 0;
  1279. static unsigned char state_timer_heater_2 = 0;
  1280. #endif
  1281. #endif
  1282. #if HEATER_BED_PIN > -1
  1283. // @@DR static unsigned char soft_pwm_b;
  1284. #ifdef SLOW_PWM_HEATERS
  1285. static unsigned char state_heater_b = 0;
  1286. static unsigned char state_timer_heater_b = 0;
  1287. #endif
  1288. #endif
  1289. #if defined(FILWIDTH_PIN) &&(FILWIDTH_PIN > -1)
  1290. static unsigned long raw_filwidth_value = 0; //added for filament width sensor
  1291. #endif
  1292. #ifndef SLOW_PWM_HEATERS
  1293. /*
  1294. * standard PWM modulation
  1295. */
  1296. if (pwm_count == 0)
  1297. {
  1298. soft_pwm_0 = soft_pwm[0];
  1299. if(soft_pwm_0 > 0)
  1300. {
  1301. WRITE(HEATER_0_PIN,1);
  1302. #ifdef HEATERS_PARALLEL
  1303. WRITE(HEATER_1_PIN,1);
  1304. #endif
  1305. } else WRITE(HEATER_0_PIN,0);
  1306. #if EXTRUDERS > 1
  1307. soft_pwm_1 = soft_pwm[1];
  1308. if(soft_pwm_1 > 0) WRITE(HEATER_1_PIN,1); else WRITE(HEATER_1_PIN,0);
  1309. #endif
  1310. #if EXTRUDERS > 2
  1311. soft_pwm_2 = soft_pwm[2];
  1312. if(soft_pwm_2 > 0) WRITE(HEATER_2_PIN,1); else WRITE(HEATER_2_PIN,0);
  1313. #endif
  1314. }
  1315. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1316. #if 0 // @@DR vypnuto pro hw pwm bedu
  1317. // tuhle prasarnu bude potreba poustet ve stanovenych intervalech, jinak nemam moc sanci zareagovat
  1318. // teoreticky by se tato cast uz vubec nemusela poustet
  1319. if ((pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1)) == 0)
  1320. {
  1321. soft_pwm_b = soft_pwm_bed >> (7 - HEATER_BED_SOFT_PWM_BITS);
  1322. # ifndef SYSTEM_TIMER_2
  1323. // tady budu krokovat pomalou frekvenci na automatu - tohle je rizeni spinani a rozepinani
  1324. // jako ridici frekvenci mam 2khz, jako vystupni frekvenci mam 30hz
  1325. // 2kHz jsou ovsem ve slysitelnem pasmu, mozna bude potreba jit s frekvenci nahoru (a tomu taky prizpusobit ostatni veci)
  1326. // Teoreticky bych mohl stahnout OCR0B citac na 6, cimz bych se dostal nekam ke 40khz a tady potom honit PWM rychleji nebo i pomaleji
  1327. // to nicemu nevadi. Soft PWM scale by se 20x zvetsilo (no dobre, 16x), cimz by se to posunulo k puvodnimu 30Hz PWM
  1328. //if(soft_pwm_b > 0) WRITE(HEATER_BED_PIN,1); else WRITE(HEATER_BED_PIN,0);
  1329. # endif //SYSTEM_TIMER_2
  1330. }
  1331. #endif
  1332. #endif
  1333. #ifdef FAN_SOFT_PWM
  1334. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1335. {
  1336. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1337. if(soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1338. }
  1339. #endif
  1340. if(soft_pwm_0 < pwm_count)
  1341. {
  1342. WRITE(HEATER_0_PIN,0);
  1343. #ifdef HEATERS_PARALLEL
  1344. WRITE(HEATER_1_PIN,0);
  1345. #endif
  1346. }
  1347. #if EXTRUDERS > 1
  1348. if(soft_pwm_1 < pwm_count) WRITE(HEATER_1_PIN,0);
  1349. #endif
  1350. #if EXTRUDERS > 2
  1351. if(soft_pwm_2 < pwm_count) WRITE(HEATER_2_PIN,0);
  1352. #endif
  1353. #if 0 // @@DR
  1354. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1355. if (soft_pwm_b < (pwm_count & ((1 << HEATER_BED_SOFT_PWM_BITS) - 1))){
  1356. //WRITE(HEATER_BED_PIN,0);
  1357. }
  1358. //WRITE(HEATER_BED_PIN, pwm_count & 1 );
  1359. #endif
  1360. #endif
  1361. #ifdef FAN_SOFT_PWM
  1362. if (soft_pwm_fan < (pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1))) WRITE(FAN_PIN,0);
  1363. #endif
  1364. pwm_count += (1 << SOFT_PWM_SCALE);
  1365. pwm_count &= 0x7f;
  1366. #else //ifndef SLOW_PWM_HEATERS
  1367. /*
  1368. * SLOW PWM HEATERS
  1369. *
  1370. * for heaters drived by relay
  1371. */
  1372. #ifndef MIN_STATE_TIME
  1373. #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds
  1374. #endif
  1375. if (slow_pwm_count == 0) {
  1376. // EXTRUDER 0
  1377. soft_pwm_0 = soft_pwm[0];
  1378. if (soft_pwm_0 > 0) {
  1379. // turn ON heather only if the minimum time is up
  1380. if (state_timer_heater_0 == 0) {
  1381. // if change state set timer
  1382. if (state_heater_0 == 0) {
  1383. state_timer_heater_0 = MIN_STATE_TIME;
  1384. }
  1385. state_heater_0 = 1;
  1386. WRITE(HEATER_0_PIN, 1);
  1387. #ifdef HEATERS_PARALLEL
  1388. WRITE(HEATER_1_PIN, 1);
  1389. #endif
  1390. }
  1391. } else {
  1392. // turn OFF heather only if the minimum time is up
  1393. if (state_timer_heater_0 == 0) {
  1394. // if change state set timer
  1395. if (state_heater_0 == 1) {
  1396. state_timer_heater_0 = MIN_STATE_TIME;
  1397. }
  1398. state_heater_0 = 0;
  1399. WRITE(HEATER_0_PIN, 0);
  1400. #ifdef HEATERS_PARALLEL
  1401. WRITE(HEATER_1_PIN, 0);
  1402. #endif
  1403. }
  1404. }
  1405. #if EXTRUDERS > 1
  1406. // EXTRUDER 1
  1407. soft_pwm_1 = soft_pwm[1];
  1408. if (soft_pwm_1 > 0) {
  1409. // turn ON heather only if the minimum time is up
  1410. if (state_timer_heater_1 == 0) {
  1411. // if change state set timer
  1412. if (state_heater_1 == 0) {
  1413. state_timer_heater_1 = MIN_STATE_TIME;
  1414. }
  1415. state_heater_1 = 1;
  1416. WRITE(HEATER_1_PIN, 1);
  1417. }
  1418. } else {
  1419. // turn OFF heather only if the minimum time is up
  1420. if (state_timer_heater_1 == 0) {
  1421. // if change state set timer
  1422. if (state_heater_1 == 1) {
  1423. state_timer_heater_1 = MIN_STATE_TIME;
  1424. }
  1425. state_heater_1 = 0;
  1426. WRITE(HEATER_1_PIN, 0);
  1427. }
  1428. }
  1429. #endif
  1430. #if EXTRUDERS > 2
  1431. // EXTRUDER 2
  1432. soft_pwm_2 = soft_pwm[2];
  1433. if (soft_pwm_2 > 0) {
  1434. // turn ON heather only if the minimum time is up
  1435. if (state_timer_heater_2 == 0) {
  1436. // if change state set timer
  1437. if (state_heater_2 == 0) {
  1438. state_timer_heater_2 = MIN_STATE_TIME;
  1439. }
  1440. state_heater_2 = 1;
  1441. WRITE(HEATER_2_PIN, 1);
  1442. }
  1443. } else {
  1444. // turn OFF heather only if the minimum time is up
  1445. if (state_timer_heater_2 == 0) {
  1446. // if change state set timer
  1447. if (state_heater_2 == 1) {
  1448. state_timer_heater_2 = MIN_STATE_TIME;
  1449. }
  1450. state_heater_2 = 0;
  1451. WRITE(HEATER_2_PIN, 0);
  1452. }
  1453. }
  1454. #endif
  1455. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1456. // BED
  1457. soft_pwm_b = soft_pwm_bed;
  1458. if (soft_pwm_b > 0) {
  1459. // turn ON heather only if the minimum time is up
  1460. if (state_timer_heater_b == 0) {
  1461. // if change state set timer
  1462. if (state_heater_b == 0) {
  1463. state_timer_heater_b = MIN_STATE_TIME;
  1464. }
  1465. state_heater_b = 1;
  1466. //WRITE(HEATER_BED_PIN, 1);
  1467. }
  1468. } else {
  1469. // turn OFF heather only if the minimum time is up
  1470. if (state_timer_heater_b == 0) {
  1471. // if change state set timer
  1472. if (state_heater_b == 1) {
  1473. state_timer_heater_b = MIN_STATE_TIME;
  1474. }
  1475. state_heater_b = 0;
  1476. WRITE(HEATER_BED_PIN, 0);
  1477. }
  1478. }
  1479. #endif
  1480. } // if (slow_pwm_count == 0)
  1481. // EXTRUDER 0
  1482. if (soft_pwm_0 < slow_pwm_count) {
  1483. // turn OFF heather only if the minimum time is up
  1484. if (state_timer_heater_0 == 0) {
  1485. // if change state set timer
  1486. if (state_heater_0 == 1) {
  1487. state_timer_heater_0 = MIN_STATE_TIME;
  1488. }
  1489. state_heater_0 = 0;
  1490. WRITE(HEATER_0_PIN, 0);
  1491. #ifdef HEATERS_PARALLEL
  1492. WRITE(HEATER_1_PIN, 0);
  1493. #endif
  1494. }
  1495. }
  1496. #if EXTRUDERS > 1
  1497. // EXTRUDER 1
  1498. if (soft_pwm_1 < slow_pwm_count) {
  1499. // turn OFF heather only if the minimum time is up
  1500. if (state_timer_heater_1 == 0) {
  1501. // if change state set timer
  1502. if (state_heater_1 == 1) {
  1503. state_timer_heater_1 = MIN_STATE_TIME;
  1504. }
  1505. state_heater_1 = 0;
  1506. WRITE(HEATER_1_PIN, 0);
  1507. }
  1508. }
  1509. #endif
  1510. #if EXTRUDERS > 2
  1511. // EXTRUDER 2
  1512. if (soft_pwm_2 < slow_pwm_count) {
  1513. // turn OFF heather only if the minimum time is up
  1514. if (state_timer_heater_2 == 0) {
  1515. // if change state set timer
  1516. if (state_heater_2 == 1) {
  1517. state_timer_heater_2 = MIN_STATE_TIME;
  1518. }
  1519. state_heater_2 = 0;
  1520. WRITE(HEATER_2_PIN, 0);
  1521. }
  1522. }
  1523. #endif
  1524. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1525. // BED
  1526. if (soft_pwm_b < slow_pwm_count) {
  1527. // turn OFF heather only if the minimum time is up
  1528. if (state_timer_heater_b == 0) {
  1529. // if change state set timer
  1530. if (state_heater_b == 1) {
  1531. state_timer_heater_b = MIN_STATE_TIME;
  1532. }
  1533. state_heater_b = 0;
  1534. WRITE(HEATER_BED_PIN, 0);
  1535. }
  1536. }
  1537. #endif
  1538. #ifdef FAN_SOFT_PWM
  1539. if ((pwm_count & ((1 << FAN_SOFT_PWM_BITS) - 1)) == 0)
  1540. soft_pwm_fan = fanSpeedSoftPwm / (1 << (8 - FAN_SOFT_PWM_BITS));
  1541. if (soft_pwm_fan > 0) WRITE(FAN_PIN,1); else WRITE(FAN_PIN,0);
  1542. }
  1543. if (soft_pwm_fan < pwm_count) WRITE(FAN_PIN,0);
  1544. #endif
  1545. pwm_count += (1 << SOFT_PWM_SCALE);
  1546. pwm_count &= 0x7f;
  1547. // increment slow_pwm_count only every 64 pwm_count circa 65.5ms
  1548. if ((pwm_count % 64) == 0) {
  1549. slow_pwm_count++;
  1550. slow_pwm_count &= 0x7f;
  1551. // Extruder 0
  1552. if (state_timer_heater_0 > 0) {
  1553. state_timer_heater_0--;
  1554. }
  1555. #if EXTRUDERS > 1
  1556. // Extruder 1
  1557. if (state_timer_heater_1 > 0)
  1558. state_timer_heater_1--;
  1559. #endif
  1560. #if EXTRUDERS > 2
  1561. // Extruder 2
  1562. if (state_timer_heater_2 > 0)
  1563. state_timer_heater_2--;
  1564. #endif
  1565. #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
  1566. // Bed
  1567. if (state_timer_heater_b > 0)
  1568. state_timer_heater_b--;
  1569. #endif
  1570. } //if ((pwm_count % 64) == 0) {
  1571. #endif //ifndef SLOW_PWM_HEATERS
  1572. #ifdef BABYSTEPPING
  1573. applyBabysteps();
  1574. #endif //BABYSTEPPING
  1575. // Check if a stack overflow happened
  1576. if (!SdFatUtil::test_stack_integrity()) stack_error();
  1577. #if (defined(FANCHECK) && defined(TACH_0) && (TACH_0 > -1))
  1578. readFanTach();
  1579. #endif //(defined(TACH_0))
  1580. }
  1581. // Timer2 (originaly timer0) is shared with millies
  1582. #ifdef SYSTEM_TIMER_2
  1583. ISR(TIMER2_COMPB_vect)
  1584. #else //SYSTEM_TIMER_2
  1585. ISR(TIMER0_COMPB_vect)
  1586. #endif //SYSTEM_TIMER_2
  1587. {
  1588. DISABLE_SOFT_PWM_INTERRUPT();
  1589. sei();
  1590. soft_pwm_isr();
  1591. cli();
  1592. ENABLE_SOFT_PWM_INTERRUPT();
  1593. }
  1594. void check_max_temp()
  1595. {
  1596. //heater
  1597. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1598. if (current_temperature_raw[0] <= maxttemp_raw[0]) {
  1599. #else
  1600. if (current_temperature_raw[0] >= maxttemp_raw[0]) {
  1601. #endif
  1602. max_temp_error(0);
  1603. }
  1604. //bed
  1605. #if defined(BED_MAXTEMP) && (TEMP_SENSOR_BED != 0)
  1606. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1607. if (current_temperature_bed_raw <= bed_maxttemp_raw) {
  1608. #else
  1609. if (current_temperature_bed_raw >= bed_maxttemp_raw) {
  1610. #endif
  1611. bed_max_temp_error();
  1612. }
  1613. #endif
  1614. //ambient
  1615. #if defined(AMBIENT_MAXTEMP) && (TEMP_SENSOR_AMBIENT != 0)
  1616. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1617. if (current_temperature_raw_ambient <= ambient_maxttemp_raw) {
  1618. #else
  1619. if (current_temperature_raw_ambient >= ambient_maxttemp_raw) {
  1620. #endif
  1621. ambient_max_temp_error();
  1622. }
  1623. #endif
  1624. }
  1625. //! number of repeating the same state with consecutive step() calls
  1626. //! used to slow down text switching
  1627. struct alert_automaton_mintemp {
  1628. const char *m2;
  1629. alert_automaton_mintemp(const char *m2):m2(m2){}
  1630. private:
  1631. enum { ALERT_AUTOMATON_SPEED_DIV = 5 };
  1632. enum class States : uint8_t { Init = 0, TempAboveMintemp, ShowPleaseRestart, ShowMintemp };
  1633. States state = States::Init;
  1634. uint8_t repeat = ALERT_AUTOMATON_SPEED_DIV;
  1635. void substep(States next_state){
  1636. if( repeat == 0 ){
  1637. state = next_state; // advance to the next state
  1638. repeat = ALERT_AUTOMATON_SPEED_DIV; // and prepare repeating for it too
  1639. } else {
  1640. --repeat;
  1641. }
  1642. }
  1643. public:
  1644. //! brief state automaton step routine
  1645. //! @param current_temp current hotend/bed temperature (for computing simple hysteresis)
  1646. //! @param mintemp minimal temperature including hysteresis to check current_temp against
  1647. void step(float current_temp, float mintemp){
  1648. static const char m1[] PROGMEM = "Please restart";
  1649. switch(state){
  1650. case States::Init: // initial state - check hysteresis
  1651. if( current_temp > mintemp ){
  1652. state = States::TempAboveMintemp;
  1653. }
  1654. // otherwise keep the Err MINTEMP alert message on the display,
  1655. // i.e. do not transfer to state 1
  1656. break;
  1657. case States::TempAboveMintemp: // the temperature has risen above the hysteresis check
  1658. lcd_setalertstatuspgm(m2);
  1659. substep(States::ShowMintemp);
  1660. last_alert_sent_to_lcd = LCDALERT_MINTEMPFIXED;
  1661. break;
  1662. case States::ShowPleaseRestart: // displaying "Please restart"
  1663. lcd_updatestatuspgm(m1);
  1664. substep(States::ShowMintemp);
  1665. last_alert_sent_to_lcd = LCDALERT_PLEASERESTART;
  1666. break;
  1667. case States::ShowMintemp: // displaying "MINTEMP fixed"
  1668. lcd_updatestatuspgm(m2);
  1669. substep(States::ShowPleaseRestart);
  1670. last_alert_sent_to_lcd = LCDALERT_MINTEMPFIXED;
  1671. break;
  1672. }
  1673. }
  1674. };
  1675. static const char m2hotend[] PROGMEM = "MINTEMP HOTEND fixed";
  1676. static const char m2bed[] PROGMEM = "MINTEMP BED fixed";
  1677. static alert_automaton_mintemp alert_automaton_hotend(m2hotend), alert_automaton_bed(m2bed);
  1678. void check_min_temp_heater0()
  1679. {
  1680. //heater
  1681. #if HEATER_0_RAW_LO_TEMP > HEATER_0_RAW_HI_TEMP
  1682. if (current_temperature_raw[0] >= minttemp_raw[0]) {
  1683. #else
  1684. if (current_temperature_raw[0] <= minttemp_raw[0]) {
  1685. #endif
  1686. menu_set_serious_error(SERIOUS_ERR_MINTEMP_HEATER);
  1687. min_temp_error(0);
  1688. } else if( menu_is_serious_error(SERIOUS_ERR_MINTEMP_HEATER) ) {
  1689. // no recovery, just force the user to restart the printer
  1690. // which is a safer variant than just continuing printing
  1691. // The automaton also checks for hysteresis - the temperature must have reached a few degrees above the MINTEMP, before
  1692. // we shall signalize, that MINTEMP has been fixed
  1693. // Code notice: normally the alert_automaton instance would have been placed here
  1694. // as static alert_automaton_mintemp alert_automaton_hotend, but
  1695. // due to stupid compiler that takes 16 more bytes.
  1696. alert_automaton_hotend.step(current_temperature[0], minttemp[0] + TEMP_HYSTERESIS);
  1697. }
  1698. }
  1699. void check_min_temp_bed()
  1700. {
  1701. #if HEATER_BED_RAW_LO_TEMP > HEATER_BED_RAW_HI_TEMP
  1702. if (current_temperature_bed_raw >= bed_minttemp_raw) {
  1703. #else
  1704. if (current_temperature_bed_raw <= bed_minttemp_raw) {
  1705. #endif
  1706. menu_set_serious_error(SERIOUS_ERR_MINTEMP_BED);
  1707. bed_min_temp_error();
  1708. } else if( menu_is_serious_error(SERIOUS_ERR_MINTEMP_BED) ){
  1709. // no recovery, just force the user to restart the printer
  1710. // which is a safer variant than just continuing printing
  1711. alert_automaton_bed.step(current_temperature_bed, BED_MINTEMP + TEMP_HYSTERESIS);
  1712. }
  1713. }
  1714. #ifdef AMBIENT_MINTEMP
  1715. void check_min_temp_ambient()
  1716. {
  1717. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1718. if (current_temperature_raw_ambient >= ambient_minttemp_raw) {
  1719. #else
  1720. if (current_temperature_raw_ambient <= ambient_minttemp_raw) {
  1721. #endif
  1722. ambient_min_temp_error();
  1723. }
  1724. }
  1725. #endif
  1726. void check_min_temp()
  1727. {
  1728. static bool bCheckingOnHeater=false; // state variable, which allows to short no-checking delay (is set, when temperature is (first time) over heaterMintemp)
  1729. static bool bCheckingOnBed=false; // state variable, which allows to short no-checking delay (is set, when temperature is (first time) over bedMintemp)
  1730. #ifdef AMBIENT_THERMISTOR
  1731. #ifdef AMBIENT_MINTEMP
  1732. check_min_temp_ambient();
  1733. #endif
  1734. #if AMBIENT_RAW_LO_TEMP > AMBIENT_RAW_HI_TEMP
  1735. if(current_temperature_raw_ambient>(OVERSAMPLENR*MINTEMP_MINAMBIENT_RAW)) // thermistor is NTC type
  1736. #else
  1737. if(current_temperature_raw_ambient=<(OVERSAMPLENR*MINTEMP_MINAMBIENT_RAW))
  1738. #endif
  1739. { // ambient temperature is low
  1740. #endif //AMBIENT_THERMISTOR
  1741. // *** 'common' part of code for MK2.5 & MK3
  1742. // * nozzle checking
  1743. if(target_temperature[active_extruder]>minttemp[active_extruder])
  1744. { // ~ nozzle heating is on
  1745. bCheckingOnHeater=bCheckingOnHeater||(current_temperature[active_extruder]>(minttemp[active_extruder]+TEMP_HYSTERESIS)); // for eventually delay cutting
  1746. if(oTimer4minTempHeater.expired(HEATER_MINTEMP_DELAY)||(!oTimer4minTempHeater.running())||bCheckingOnHeater)
  1747. {
  1748. bCheckingOnHeater=true; // not necessary
  1749. check_min_temp_heater0(); // delay is elapsed or temperature is/was over minTemp => periodical checking is active
  1750. }
  1751. }
  1752. else { // ~ nozzle heating is off
  1753. oTimer4minTempHeater.start();
  1754. bCheckingOnHeater=false;
  1755. }
  1756. // * bed checking
  1757. if(target_temperature_bed>BED_MINTEMP)
  1758. { // ~ bed heating is on
  1759. bCheckingOnBed=bCheckingOnBed||(current_temperature_bed>(BED_MINTEMP+TEMP_HYSTERESIS)); // for eventually delay cutting
  1760. if(oTimer4minTempBed.expired(BED_MINTEMP_DELAY)||(!oTimer4minTempBed.running())||bCheckingOnBed)
  1761. {
  1762. bCheckingOnBed=true; // not necessary
  1763. check_min_temp_bed(); // delay is elapsed or temperature is/was over minTemp => periodical checking is active
  1764. }
  1765. }
  1766. else { // ~ bed heating is off
  1767. oTimer4minTempBed.start();
  1768. bCheckingOnBed=false;
  1769. }
  1770. // *** end of 'common' part
  1771. #ifdef AMBIENT_THERMISTOR
  1772. }
  1773. else { // ambient temperature is standard
  1774. check_min_temp_heater0();
  1775. check_min_temp_bed();
  1776. }
  1777. #endif //AMBIENT_THERMISTOR
  1778. }
  1779. #ifdef PIDTEMP
  1780. // Apply the scale factors to the PID values
  1781. float scalePID_i(float i)
  1782. {
  1783. return i*PID_dT;
  1784. }
  1785. float unscalePID_i(float i)
  1786. {
  1787. return i/PID_dT;
  1788. }
  1789. float scalePID_d(float d)
  1790. {
  1791. return d/PID_dT;
  1792. }
  1793. float unscalePID_d(float d)
  1794. {
  1795. return d*PID_dT;
  1796. }
  1797. #endif //PIDTEMP
  1798. #ifdef PINDA_THERMISTOR
  1799. //! @brief PINDA thermistor detected
  1800. //!
  1801. //! @retval true firmware should do temperature compensation and allow calibration
  1802. //! @retval false PINDA thermistor is not detected, disable temperature compensation and calibration
  1803. //! @retval true/false when forced via LCD menu Settings->HW Setup->SuperPINDA
  1804. //!
  1805. bool has_temperature_compensation()
  1806. {
  1807. #ifdef SUPERPINDA_SUPPORT
  1808. #ifdef PINDA_TEMP_COMP
  1809. uint8_t pinda_temp_compensation = eeprom_read_byte((uint8_t*)EEPROM_PINDA_TEMP_COMPENSATION);
  1810. if (pinda_temp_compensation == EEPROM_EMPTY_VALUE) //Unkown PINDA temp compenstation, so check it.
  1811. {
  1812. #endif //PINDA_TEMP_COMP
  1813. return (current_temperature_pinda >= PINDA_MINTEMP) ? true : false;
  1814. #ifdef PINDA_TEMP_COMP
  1815. }
  1816. else if (pinda_temp_compensation == 0) return true; //Overwritten via LCD menu SuperPINDA [No]
  1817. else return false; //Overwritten via LCD menu SuperPINDA [YES]
  1818. #endif //PINDA_TEMP_COMP
  1819. #else
  1820. return true;
  1821. #endif
  1822. }
  1823. #endif //PINDA_THERMISTOR