temperature.cpp 60 KB

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