temperature.cpp 59 KB

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