temperature.cpp 60 KB

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