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

MarlinCore.cpp 31KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/grbl/grbl
  28. */
  29. #include "MarlinCore.h"
  30. #include "HAL/shared/Delay.h"
  31. #include "HAL/shared/esp_wifi.h"
  32. #ifdef ARDUINO
  33. #include <pins_arduino.h>
  34. #endif
  35. #include <math.h>
  36. #include "core/utility.h"
  37. #include "lcd/ultralcd.h"
  38. #include "module/motion.h"
  39. #include "module/planner.h"
  40. #include "module/stepper.h"
  41. #include "module/endstops.h"
  42. #include "module/probe.h"
  43. #include "module/temperature.h"
  44. #include "sd/cardreader.h"
  45. #include "module/configuration_store.h"
  46. #include "module/printcounter.h" // PrintCounter or Stopwatch
  47. #include "feature/closedloop.h"
  48. #include "module/stepper/indirection.h"
  49. #include "libs/nozzle.h"
  50. #include "gcode/gcode.h"
  51. #include "gcode/parser.h"
  52. #include "gcode/queue.h"
  53. #if ENABLED(TOUCH_BUTTONS)
  54. #include "feature/touch/xpt2046.h"
  55. #endif
  56. #if ENABLED(HOST_ACTION_COMMANDS)
  57. #include "feature/host_actions.h"
  58. #endif
  59. #if USE_BEEPER
  60. #include "libs/buzzer.h"
  61. #endif
  62. #if HAS_I2C_DIGIPOT
  63. #include "feature/digipot/digipot.h"
  64. #endif
  65. #if ENABLED(MIXING_EXTRUDER)
  66. #include "feature/mixing.h"
  67. #endif
  68. #if ENABLED(MAX7219_DEBUG)
  69. #include "feature/max7219.h"
  70. #endif
  71. #if HAS_COLOR_LEDS
  72. #include "feature/leds/leds.h"
  73. #endif
  74. #if ENABLED(BLTOUCH)
  75. #include "feature/bltouch.h"
  76. #endif
  77. #if ENABLED(POLL_JOG)
  78. #include "feature/joystick.h"
  79. #endif
  80. #if HAS_SERVOS
  81. #include "module/servo.h"
  82. #endif
  83. #if ENABLED(DAC_STEPPER_CURRENT)
  84. #include "feature/dac/stepper_dac.h"
  85. #endif
  86. #if ENABLED(EXPERIMENTAL_I2CBUS)
  87. #include "feature/twibus.h"
  88. TWIBus i2c;
  89. #endif
  90. #if ENABLED(I2C_POSITION_ENCODERS)
  91. #include "feature/encoder_i2c.h"
  92. #endif
  93. #if HAS_TRINAMIC_CONFIG && DISABLED(PSU_DEFAULT_OFF)
  94. #include "feature/tmc_util.h"
  95. #endif
  96. #if HAS_CUTTER
  97. #include "feature/spindle_laser.h"
  98. #endif
  99. #if ENABLED(SDSUPPORT)
  100. CardReader card;
  101. #endif
  102. #if ENABLED(G38_PROBE_TARGET)
  103. uint8_t G38_move; // = 0
  104. bool G38_did_trigger; // = false
  105. #endif
  106. #if ENABLED(DELTA)
  107. #include "module/delta.h"
  108. #elif IS_SCARA
  109. #include "module/scara.h"
  110. #endif
  111. #if HAS_LEVELING
  112. #include "feature/bedlevel/bedlevel.h"
  113. #endif
  114. #if BOTH(ADVANCED_PAUSE_FEATURE, PAUSE_PARK_NO_STEPPER_TIMEOUT)
  115. #include "feature/pause.h"
  116. #endif
  117. #if ENABLED(POWER_LOSS_RECOVERY)
  118. #include "feature/powerloss.h"
  119. #endif
  120. #if ENABLED(CANCEL_OBJECTS)
  121. #include "feature/cancel_object.h"
  122. #endif
  123. #if HAS_FILAMENT_SENSOR
  124. #include "feature/runout.h"
  125. #endif
  126. #if ENABLED(TEMP_STAT_LEDS)
  127. #include "feature/leds/tempstat.h"
  128. #endif
  129. #if HAS_CASE_LIGHT
  130. #include "feature/caselight.h"
  131. #endif
  132. #if HAS_FANMUX
  133. #include "feature/fanmux.h"
  134. #endif
  135. #if DO_SWITCH_EXTRUDER || ANY(SWITCHING_NOZZLE, PARKING_EXTRUDER, MAGNETIC_PARKING_EXTRUDER, ELECTROMAGNETIC_SWITCHING_TOOLHEAD, SWITCHING_TOOLHEAD)
  136. #include "module/tool_change.h"
  137. #endif
  138. #if ENABLED(USE_CONTROLLER_FAN)
  139. #include "feature/controllerfan.h"
  140. #endif
  141. #if ENABLED(PRUSA_MMU2)
  142. #include "feature/mmu2/mmu2.h"
  143. #endif
  144. #if HAS_L64XX
  145. #include "libs/L64XX/L64XX_Marlin.h"
  146. #endif
  147. const char NUL_STR[] PROGMEM = "",
  148. M112_KILL_STR[] PROGMEM = "M112 Shutdown",
  149. G28_STR[] PROGMEM = "G28",
  150. M21_STR[] PROGMEM = "M21",
  151. M23_STR[] PROGMEM = "M23 %s",
  152. M24_STR[] PROGMEM = "M24",
  153. SP_P_STR[] PROGMEM = " P",
  154. SP_T_STR[] PROGMEM = " T",
  155. SP_X_STR[] PROGMEM = " X",
  156. SP_Y_STR[] PROGMEM = " Y",
  157. SP_Z_STR[] PROGMEM = " Z",
  158. SP_E_STR[] PROGMEM = " E",
  159. X_LBL[] PROGMEM = "X:",
  160. Y_LBL[] PROGMEM = "Y:",
  161. Z_LBL[] PROGMEM = "Z:",
  162. E_LBL[] PROGMEM = "E:",
  163. SP_X_LBL[] PROGMEM = " X:",
  164. SP_Y_LBL[] PROGMEM = " Y:",
  165. SP_Z_LBL[] PROGMEM = " Z:",
  166. SP_E_LBL[] PROGMEM = " E:";
  167. MarlinState marlin_state = MF_INITIALIZING;
  168. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  169. bool wait_for_heatup = true;
  170. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  171. #if HAS_RESUME_CONTINUE
  172. bool wait_for_user; // = false;
  173. void wait_for_user_response(millis_t ms/*=0*/, const bool no_sleep/*=false*/) {
  174. TERN(ADVANCED_PAUSE_FEATURE,,UNUSED(no_sleep));
  175. KEEPALIVE_STATE(PAUSED_FOR_USER);
  176. wait_for_user = true;
  177. if (ms) ms += millis(); // expire time
  178. while (wait_for_user && !(ms && ELAPSED(millis(), ms)))
  179. idle(TERN_(ADVANCED_PAUSE_FEATURE, no_sleep));
  180. wait_for_user = false;
  181. }
  182. #endif
  183. // Inactivity shutdown
  184. millis_t max_inactive_time, // = 0
  185. stepper_inactive_time = SEC_TO_MS(DEFAULT_STEPPER_DEACTIVE_TIME);
  186. #if PIN_EXISTS(CHDK)
  187. extern millis_t chdk_timeout;
  188. #endif
  189. #if ENABLED(I2C_POSITION_ENCODERS)
  190. I2CPositionEncodersMgr I2CPEM;
  191. #endif
  192. /**
  193. * ***************************************************************************
  194. * ******************************** FUNCTIONS ********************************
  195. * ***************************************************************************
  196. */
  197. void setup_killpin() {
  198. #if HAS_KILL
  199. #if KILL_PIN_STATE
  200. SET_INPUT_PULLDOWN(KILL_PIN);
  201. #else
  202. SET_INPUT_PULLUP(KILL_PIN);
  203. #endif
  204. #endif
  205. }
  206. void setup_powerhold() {
  207. #if HAS_SUICIDE
  208. OUT_WRITE(SUICIDE_PIN, !SUICIDE_PIN_INVERTING);
  209. #endif
  210. #if ENABLED(PSU_CONTROL)
  211. powersupply_on = ENABLED(PSU_DEFAULT_OFF);
  212. if (ENABLED(PSU_DEFAULT_OFF)) PSU_OFF(); else PSU_ON();
  213. #endif
  214. }
  215. /**
  216. * Stepper Reset (RigidBoard, et.al.)
  217. */
  218. #if HAS_STEPPER_RESET
  219. void disableStepperDrivers() { OUT_WRITE(STEPPER_RESET_PIN, LOW); } // Drive down to keep motor driver chips in reset
  220. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // Set to input, allowing pullups to pull the pin high
  221. #endif
  222. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  223. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  224. i2c.receive(bytes);
  225. }
  226. void i2c_on_request() { // just send dummy data for now
  227. i2c.reply("Hello World!\n");
  228. }
  229. #endif
  230. /**
  231. * Sensitive pin test for M42, M226
  232. */
  233. #include "pins/sensitive_pins.h"
  234. #pragma GCC diagnostic push
  235. #pragma GCC diagnostic ignored "-Wnarrowing"
  236. bool pin_is_protected(const pin_t pin) {
  237. static const pin_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  238. LOOP_L_N(i, COUNT(sensitive_pins)) {
  239. pin_t sensitive_pin;
  240. memcpy_P(&sensitive_pin, &sensitive_pins[i], sizeof(pin_t));
  241. if (pin == sensitive_pin) return true;
  242. }
  243. return false;
  244. }
  245. #pragma GCC diagnostic pop
  246. void protected_pin_err() {
  247. SERIAL_ERROR_MSG(STR_ERR_PROTECTED_PIN);
  248. }
  249. void quickstop_stepper() {
  250. planner.quick_stop();
  251. planner.synchronize();
  252. set_current_from_steppers_for_axis(ALL_AXES);
  253. sync_plan_position();
  254. }
  255. void enable_e_steppers() {
  256. #define _ENA_E(N) ENABLE_AXIS_E##N();
  257. REPEAT(E_STEPPERS, _ENA_E)
  258. }
  259. void enable_all_steppers() {
  260. TERN_(AUTO_POWER_CONTROL, powerManager.power_on());
  261. ENABLE_AXIS_X();
  262. ENABLE_AXIS_Y();
  263. ENABLE_AXIS_Z();
  264. enable_e_steppers();
  265. }
  266. void disable_e_steppers() {
  267. #define _DIS_E(N) DISABLE_AXIS_E##N();
  268. REPEAT(E_STEPPERS, _DIS_E)
  269. }
  270. void disable_e_stepper(const uint8_t e) {
  271. #define _CASE_DIS_E(N) case N: DISABLE_AXIS_E##N(); break;
  272. switch (e) {
  273. REPEAT(EXTRUDERS, _CASE_DIS_E)
  274. }
  275. }
  276. void disable_all_steppers() {
  277. DISABLE_AXIS_X();
  278. DISABLE_AXIS_Y();
  279. DISABLE_AXIS_Z();
  280. disable_e_steppers();
  281. }
  282. #if ENABLED(G29_RETRY_AND_RECOVER)
  283. void event_probe_failure() {
  284. #ifdef ACTION_ON_G29_FAILURE
  285. host_action(PSTR(ACTION_ON_G29_FAILURE));
  286. #endif
  287. #ifdef G29_FAILURE_COMMANDS
  288. gcode.process_subcommands_now_P(PSTR(G29_FAILURE_COMMANDS));
  289. #endif
  290. #if ENABLED(G29_HALT_ON_FAILURE)
  291. #ifdef ACTION_ON_CANCEL
  292. host_action_cancel();
  293. #endif
  294. kill(GET_TEXT(MSG_LCD_PROBING_FAILED));
  295. #endif
  296. }
  297. void event_probe_recover() {
  298. TERN_(HOST_PROMPT_SUPPORT, host_prompt_do(PROMPT_INFO, PSTR("G29 Retrying"), DISMISS_STR));
  299. #ifdef ACTION_ON_G29_RECOVER
  300. host_action(PSTR(ACTION_ON_G29_RECOVER));
  301. #endif
  302. #ifdef G29_RECOVER_COMMANDS
  303. gcode.process_subcommands_now_P(PSTR(G29_RECOVER_COMMANDS));
  304. #endif
  305. }
  306. #endif
  307. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  308. #include "feature/pause.h"
  309. #else
  310. constexpr bool did_pause_print = false;
  311. #endif
  312. /**
  313. * Printing is active when the print job timer is running
  314. */
  315. bool printingIsActive() {
  316. return !did_pause_print && (print_job_timer.isRunning() || IS_SD_PRINTING());
  317. }
  318. /**
  319. * Printing is paused according to SD or host indicators
  320. */
  321. bool printingIsPaused() {
  322. return did_pause_print || print_job_timer.isPaused() || IS_SD_PAUSED();
  323. }
  324. void startOrResumeJob() {
  325. if (!printingIsPaused()) {
  326. TERN_(CANCEL_OBJECTS, cancelable.reset());
  327. TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator = 0);
  328. #if BOTH(LCD_SET_PROGRESS_MANUALLY, USE_M73_REMAINING_TIME)
  329. ui.reset_remaining_time();
  330. #endif
  331. }
  332. print_job_timer.start();
  333. }
  334. #if ENABLED(SDSUPPORT)
  335. inline void abortSDPrinting() {
  336. card.endFilePrint(TERN_(SD_RESORT, true));
  337. queue.clear();
  338. quickstop_stepper();
  339. print_job_timer.stop();
  340. #if DISABLED(SD_ABORT_NO_COOLDOWN)
  341. thermalManager.disable_all_heaters();
  342. #endif
  343. #if !HAS_CUTTER
  344. thermalManager.zero_fan_speeds();
  345. #else
  346. cutter.kill(); // Full cutter shutdown including ISR control
  347. #endif
  348. wait_for_heatup = false;
  349. TERN_(POWER_LOSS_RECOVERY, recovery.purge());
  350. #ifdef EVENT_GCODE_SD_STOP
  351. queue.inject_P(PSTR(EVENT_GCODE_SD_STOP));
  352. #endif
  353. }
  354. inline void finishSDPrinting() {
  355. if (queue.enqueue_one_P(PSTR("M1001")))
  356. marlin_state = MF_RUNNING;
  357. }
  358. #endif // SDSUPPORT
  359. /**
  360. * Minimal management of Marlin's core activities:
  361. * - Keep the command buffer full
  362. * - Check for maximum inactive time between commands
  363. * - Check for maximum inactive time between stepper commands
  364. * - Check if CHDK_PIN needs to go LOW
  365. * - Check for KILL button held down
  366. * - Check for HOME button held down
  367. * - Check if cooling fan needs to be switched on
  368. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  369. * - Pulse FET_SAFETY_PIN if it exists
  370. */
  371. inline void manage_inactivity(const bool ignore_stepper_queue=false) {
  372. if (queue.length < BUFSIZE) queue.get_available_commands();
  373. const millis_t ms = millis();
  374. if (max_inactive_time && ELAPSED(ms, gcode.previous_move_ms + max_inactive_time)) {
  375. SERIAL_ERROR_START();
  376. SERIAL_ECHOLNPAIR(STR_KILL_INACTIVE_TIME, parser.command_ptr);
  377. kill();
  378. }
  379. // Prevent steppers timing-out in the middle of M600
  380. #define STAY_TEST (BOTH(ADVANCED_PAUSE_FEATURE, PAUSE_PARK_NO_STEPPER_TIMEOUT) && did_pause_print)
  381. if (stepper_inactive_time) {
  382. static bool already_shutdown_steppers; // = false
  383. if (planner.has_blocks_queued())
  384. gcode.reset_stepper_timeout();
  385. else if (!STAY_TEST && !ignore_stepper_queue && ELAPSED(ms, gcode.previous_move_ms + stepper_inactive_time)) {
  386. if (!already_shutdown_steppers) {
  387. already_shutdown_steppers = true; // L6470 SPI will consume 99% of free time without this
  388. if (ENABLED(DISABLE_INACTIVE_X)) DISABLE_AXIS_X();
  389. if (ENABLED(DISABLE_INACTIVE_Y)) DISABLE_AXIS_Y();
  390. if (ENABLED(DISABLE_INACTIVE_Z)) DISABLE_AXIS_Z();
  391. if (ENABLED(DISABLE_INACTIVE_E)) disable_e_steppers();
  392. #if BOTH(HAS_LCD_MENU, AUTO_BED_LEVELING_UBL)
  393. if (ubl.lcd_map_control) {
  394. ubl.lcd_map_control = false;
  395. ui.defer_status_screen(false);
  396. }
  397. #endif
  398. }
  399. }
  400. else
  401. already_shutdown_steppers = false;
  402. }
  403. #if PIN_EXISTS(CHDK) // Check if pin should be set to LOW (after M240 set it HIGH)
  404. if (chdk_timeout && ELAPSED(ms, chdk_timeout)) {
  405. chdk_timeout = 0;
  406. WRITE(CHDK_PIN, LOW);
  407. }
  408. #endif
  409. #if HAS_KILL
  410. // Check if the kill button was pressed and wait just in case it was an accidental
  411. // key kill key press
  412. // -------------------------------------------------------------------------------
  413. static int killCount = 0; // make the inactivity button a bit less responsive
  414. const int KILL_DELAY = 750;
  415. if (kill_state())
  416. killCount++;
  417. else if (killCount > 0)
  418. killCount--;
  419. // Exceeded threshold and we can confirm that it was not accidental
  420. // KILL the machine
  421. // ----------------------------------------------------------------
  422. if (killCount >= KILL_DELAY) {
  423. SERIAL_ERROR_MSG(STR_KILL_BUTTON);
  424. kill();
  425. }
  426. #endif
  427. #if HAS_HOME
  428. // Handle a standalone HOME button
  429. constexpr millis_t HOME_DEBOUNCE_DELAY = 1000UL;
  430. static millis_t next_home_key_ms; // = 0
  431. if (!IS_SD_PRINTING() && !READ(HOME_PIN)) { // HOME_PIN goes LOW when pressed
  432. const millis_t ms = millis();
  433. if (ELAPSED(ms, next_home_key_ms)) {
  434. next_home_key_ms = ms + HOME_DEBOUNCE_DELAY;
  435. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  436. queue.enqueue_now_P(G28_STR);
  437. }
  438. }
  439. #endif
  440. TERN_(USE_CONTROLLER_FAN, controllerFan.update()); // Check if fan should be turned on to cool stepper drivers down
  441. TERN_(AUTO_POWER_CONTROL, powerManager.check());
  442. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  443. if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP
  444. && ELAPSED(ms, gcode.previous_move_ms + SEC_TO_MS(EXTRUDER_RUNOUT_SECONDS))
  445. && !planner.has_blocks_queued()
  446. ) {
  447. #if ENABLED(SWITCHING_EXTRUDER)
  448. bool oldstatus;
  449. switch (active_extruder) {
  450. default: oldstatus = E0_ENABLE_READ(); ENABLE_AXIS_E0(); break;
  451. #if E_STEPPERS > 1
  452. case 2: case 3: oldstatus = E1_ENABLE_READ(); ENABLE_AXIS_E1(); break;
  453. #if E_STEPPERS > 2
  454. case 4: case 5: oldstatus = E2_ENABLE_READ(); ENABLE_AXIS_E2(); break;
  455. #if E_STEPPERS > 3
  456. case 6: case 7: oldstatus = E3_ENABLE_READ(); ENABLE_AXIS_E3(); break;
  457. #endif // E_STEPPERS > 3
  458. #endif // E_STEPPERS > 2
  459. #endif // E_STEPPERS > 1
  460. }
  461. #else // !SWITCHING_EXTRUDER
  462. bool oldstatus;
  463. switch (active_extruder) {
  464. default:
  465. #define _CASE_EN(N) case N: oldstatus = E##N##_ENABLE_READ(); ENABLE_AXIS_E##N(); break;
  466. REPEAT(E_STEPPERS, _CASE_EN);
  467. }
  468. #endif
  469. const float olde = current_position.e;
  470. current_position.e += EXTRUDER_RUNOUT_EXTRUDE;
  471. line_to_current_position(MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED));
  472. current_position.e = olde;
  473. planner.set_e_position_mm(olde);
  474. planner.synchronize();
  475. #if ENABLED(SWITCHING_EXTRUDER)
  476. switch (active_extruder) {
  477. default: oldstatus = E0_ENABLE_WRITE(oldstatus); break;
  478. #if E_STEPPERS > 1
  479. case 2: case 3: oldstatus = E1_ENABLE_WRITE(oldstatus); break;
  480. #if E_STEPPERS > 2
  481. case 4: case 5: oldstatus = E2_ENABLE_WRITE(oldstatus); break;
  482. #endif // E_STEPPERS > 2
  483. #endif // E_STEPPERS > 1
  484. }
  485. #else // !SWITCHING_EXTRUDER
  486. switch (active_extruder) {
  487. #define _CASE_RESTORE(N) case N: E##N##_ENABLE_WRITE(oldstatus); break;
  488. REPEAT(E_STEPPERS, _CASE_RESTORE);
  489. }
  490. #endif // !SWITCHING_EXTRUDER
  491. gcode.reset_stepper_timeout();
  492. }
  493. #endif // EXTRUDER_RUNOUT_PREVENT
  494. #if ENABLED(DUAL_X_CARRIAGE)
  495. // handle delayed move timeout
  496. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  497. // travel moves have been received so enact them
  498. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  499. destination = current_position;
  500. prepare_line_to_destination();
  501. }
  502. #endif
  503. TERN_(TEMP_STAT_LEDS, handle_status_leds());
  504. TERN_(MONITOR_DRIVER_STATUS, monitor_tmc_drivers());
  505. TERN_(MONITOR_L6470_DRIVER_STATUS, L64xxManager.monitor_driver());
  506. // Limit check_axes_activity frequency to 10Hz
  507. static millis_t next_check_axes_ms = 0;
  508. if (ELAPSED(ms, next_check_axes_ms)) {
  509. planner.check_axes_activity();
  510. next_check_axes_ms = ms + 100UL;
  511. }
  512. #if PIN_EXISTS(FET_SAFETY)
  513. static millis_t FET_next;
  514. if (ELAPSED(ms, FET_next)) {
  515. FET_next = ms + FET_SAFETY_DELAY; // 2µs pulse every FET_SAFETY_DELAY mS
  516. OUT_WRITE(FET_SAFETY_PIN, !FET_SAFETY_INVERTED);
  517. DELAY_US(2);
  518. WRITE(FET_SAFETY_PIN, FET_SAFETY_INVERTED);
  519. }
  520. #endif
  521. }
  522. /**
  523. * Standard idle routine keeps the machine alive:
  524. * - Core Marlin activities
  525. * - Manage heaters (and Watchdog)
  526. * - Max7219 heartbeat, animation, etc.
  527. *
  528. * Only after setup() is complete:
  529. * - Handle filament runout sensors
  530. * - Run HAL idle tasks
  531. * - Handle Power-Loss Recovery
  532. * - Run StallGuard endstop checks
  533. * - Handle SD Card insert / remove
  534. * - Handle USB Flash Drive insert / remove
  535. * - Announce Host Keepalive state (if any)
  536. * - Update the Print Job Timer state
  537. * - Update the Beeper queue
  538. * - Read Buttons and Update the LCD
  539. * - Run i2c Position Encoders
  540. * - Auto-report Temperatures / SD Status
  541. * - Update the Prusa MMU2
  542. * - Handle Joystick jogging
  543. */
  544. void idle(TERN_(ADVANCED_PAUSE_FEATURE, bool no_stepper_sleep/*=false*/)) {
  545. // Core Marlin activities
  546. manage_inactivity(TERN_(ADVANCED_PAUSE_FEATURE, no_stepper_sleep));
  547. // Manage Heaters (and Watchdog)
  548. thermalManager.manage_heater();
  549. // Max7219 heartbeat, animation, etc
  550. TERN_(MAX7219_DEBUG, max7219.idle_tasks());
  551. // Return if setup() isn't completed
  552. if (marlin_state == MF_INITIALIZING) return;
  553. // Handle filament runout sensors
  554. TERN_(HAS_FILAMENT_SENSOR, runout.run());
  555. // Run HAL idle tasks
  556. #ifdef HAL_IDLETASK
  557. HAL_idletask();
  558. #endif
  559. // Handle Power-Loss Recovery
  560. #if ENABLED(POWER_LOSS_RECOVERY) && PIN_EXISTS(POWER_LOSS)
  561. recovery.outage();
  562. #endif
  563. // Run StallGuard endstop checks
  564. #if ENABLED(SPI_ENDSTOPS)
  565. if (endstops.tmc_spi_homing.any
  566. && TERN1(IMPROVE_HOMING_RELIABILITY, ELAPSED(millis(), sg_guard_period))
  567. ) LOOP_L_N(i, 4) // Read SGT 4 times per idle loop
  568. if (endstops.tmc_spi_homing_check()) break;
  569. #endif
  570. // Handle SD Card insert / remove
  571. TERN_(SDSUPPORT, card.manage_media());
  572. // Handle USB Flash Drive insert / remove
  573. TERN_(USB_FLASH_DRIVE_SUPPORT, Sd2Card::idle());
  574. // Announce Host Keepalive state (if any)
  575. TERN_(HOST_KEEPALIVE_FEATURE, gcode.host_keepalive());
  576. // Update the Print Job Timer state
  577. TERN_(PRINTCOUNTER, print_job_timer.tick());
  578. // Update the Beeper queue
  579. TERN_(USE_BEEPER, buzzer.tick());
  580. // Read Buttons and Update the LCD
  581. ui.update();
  582. // Run i2c Position Encoders
  583. #if ENABLED(I2C_POSITION_ENCODERS)
  584. static millis_t i2cpem_next_update_ms;
  585. if (planner.has_blocks_queued()) {
  586. const millis_t ms = millis();
  587. if (ELAPSED(ms, i2cpem_next_update_ms)) {
  588. I2CPEM.update();
  589. i2cpem_next_update_ms = ms + I2CPE_MIN_UPD_TIME_MS;
  590. }
  591. }
  592. #endif
  593. // Auto-report Temperatures / SD Status
  594. #if HAS_AUTO_REPORTING
  595. if (!gcode.autoreport_paused) {
  596. TERN_(AUTO_REPORT_TEMPERATURES, thermalManager.auto_report_temperatures());
  597. TERN_(AUTO_REPORT_SD_STATUS, card.auto_report_sd_status());
  598. }
  599. #endif
  600. // Update the Prusa MMU2
  601. TERN_(PRUSA_MMU2, mmu2.mmu_loop());
  602. // Handle Joystick jogging
  603. TERN_(POLL_JOG, joystick.inject_jog_moves());
  604. }
  605. /**
  606. * Kill all activity and lock the machine.
  607. * After this the machine will need to be reset.
  608. */
  609. void kill(PGM_P const lcd_error/*=nullptr*/, PGM_P const lcd_component/*=nullptr*/, const bool steppers_off/*=false*/) {
  610. thermalManager.disable_all_heaters();
  611. TERN_(HAS_CUTTER, cutter.kill()); // Full cutter shutdown including ISR control
  612. SERIAL_ERROR_MSG(STR_ERR_KILLED);
  613. #if HAS_DISPLAY
  614. ui.kill_screen(lcd_error ?: GET_TEXT(MSG_KILLED), lcd_component ?: NUL_STR);
  615. #else
  616. UNUSED(lcd_error);
  617. UNUSED(lcd_component);
  618. #endif
  619. #ifdef ACTION_ON_KILL
  620. host_action_kill();
  621. #endif
  622. minkill(steppers_off);
  623. }
  624. void minkill(const bool steppers_off/*=false*/) {
  625. // Wait a short time (allows messages to get out before shutting down.
  626. for (int i = 1000; i--;) DELAY_US(600);
  627. cli(); // Stop interrupts
  628. // Wait to ensure all interrupts stopped
  629. for (int i = 1000; i--;) DELAY_US(250);
  630. // Reiterate heaters off
  631. thermalManager.disable_all_heaters();
  632. TERN_(HAS_CUTTER, cutter.kill()); // Reiterate cutter shutdown
  633. // Power off all steppers (for M112) or just the E steppers
  634. steppers_off ? disable_all_steppers() : disable_e_steppers();
  635. TERN_(PSU_CONTROL, PSU_OFF());
  636. TERN_(HAS_SUICIDE, suicide());
  637. #if HAS_KILL
  638. // Wait for kill to be released
  639. while (kill_state()) watchdog_refresh();
  640. // Wait for kill to be pressed
  641. while (!kill_state()) watchdog_refresh();
  642. void (*resetFunc)() = 0; // Declare resetFunc() at address 0
  643. resetFunc(); // Jump to address 0
  644. #else
  645. for (;;) watchdog_refresh(); // Wait for reset
  646. #endif
  647. }
  648. /**
  649. * Turn off heaters and stop the print in progress
  650. * After a stop the machine may be resumed with M999
  651. */
  652. void stop() {
  653. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  654. print_job_timer.stop();
  655. #if ENABLED(PROBING_FANS_OFF)
  656. if (thermalManager.fans_paused) thermalManager.set_fans_paused(false); // put things back the way they were
  657. #endif
  658. if (IsRunning()) {
  659. SERIAL_ERROR_MSG(STR_ERR_STOPPED);
  660. LCD_MESSAGEPGM(MSG_STOPPED);
  661. safe_delay(350); // allow enough time for messages to get out before stopping
  662. marlin_state = MF_STOPPED;
  663. }
  664. }
  665. /**
  666. * Marlin entry-point: Set up before the program loop
  667. * - Set up the kill pin, filament runout, power hold
  668. * - Start the serial port
  669. * - Print startup messages and diagnostics
  670. * - Get EEPROM or default settings
  671. * - Initialize managers for:
  672. * • temperature
  673. * • planner
  674. * • watchdog
  675. * • stepper
  676. * • photo pin
  677. * • servos
  678. * • LCD controller
  679. * • Digipot I2C
  680. * • Z probe sled
  681. * • status LEDs
  682. * • Max7219
  683. */
  684. void setup() {
  685. #if ENABLED(MARLIN_DEV_MODE)
  686. auto log_current_ms = [&](PGM_P const msg) {
  687. SERIAL_ECHO_START();
  688. SERIAL_CHAR('['); SERIAL_ECHO(millis()); SERIAL_ECHO("] ");
  689. serialprintPGM(msg);
  690. SERIAL_EOL();
  691. };
  692. #define SETUP_LOG(M) log_current_ms(PSTR(M))
  693. #else
  694. #define SETUP_LOG(...) NOOP
  695. #endif
  696. #define SETUP_RUN(C) do{ SETUP_LOG(STRINGIFY(C)); C; }while(0)
  697. #if EITHER(DISABLE_DEBUG, DISABLE_JTAG)
  698. // Disable any hardware debug to free up pins for IO
  699. #if ENABLED(DISABLE_DEBUG) && defined(JTAGSWD_DISABLE)
  700. JTAGSWD_DISABLE();
  701. #elif defined(JTAG_DISABLE)
  702. JTAG_DISABLE();
  703. #else
  704. #error "DISABLE_(DEBUG|JTAG) is not supported for the selected MCU/Board."
  705. #endif
  706. #endif
  707. #if NUM_SERIAL > 0
  708. MYSERIAL0.begin(BAUDRATE);
  709. uint32_t serial_connect_timeout = millis() + 1000UL;
  710. while (!MYSERIAL0 && PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
  711. #if NUM_SERIAL > 1
  712. MYSERIAL1.begin(BAUDRATE);
  713. serial_connect_timeout = millis() + 1000UL;
  714. while (!MYSERIAL1 && PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
  715. #endif
  716. SERIAL_ECHO_MSG("start");
  717. #endif
  718. SETUP_RUN(HAL_init());
  719. #if HAS_L64XX
  720. SETUP_RUN(L64xxManager.init()); // Set up SPI, init drivers
  721. #endif
  722. #if ENABLED(SMART_EFFECTOR) && PIN_EXISTS(SMART_EFFECTOR_MOD)
  723. OUT_WRITE(SMART_EFFECTOR_MOD_PIN, LOW); // Put Smart Effector into NORMAL mode
  724. #endif
  725. #if HAS_FILAMENT_SENSOR
  726. SETUP_RUN(runout.setup());
  727. #endif
  728. #if ENABLED(POWER_LOSS_RECOVERY)
  729. SETUP_RUN(recovery.setup());
  730. #endif
  731. SETUP_RUN(setup_killpin());
  732. #if HAS_TMC220x
  733. SETUP_RUN(tmc_serial_begin());
  734. #endif
  735. SETUP_RUN(setup_powerhold());
  736. #if HAS_STEPPER_RESET
  737. SETUP_RUN(disableStepperDrivers());
  738. #endif
  739. #if HAS_TMC_SPI
  740. #if DISABLED(TMC_USE_SW_SPI)
  741. SETUP_RUN(SPI.begin());
  742. #endif
  743. SETUP_RUN(tmc_init_cs_pins());
  744. #endif
  745. #ifdef BOARD_INIT
  746. SETUP_LOG("BOARD_INIT");
  747. BOARD_INIT();
  748. #endif
  749. SETUP_RUN(esp_wifi_init());
  750. // Check startup - does nothing if bootloader sets MCUSR to 0
  751. const byte mcu = HAL_get_reset_source();
  752. if (mcu & 1) SERIAL_ECHOLNPGM(STR_POWERUP);
  753. if (mcu & 2) SERIAL_ECHOLNPGM(STR_EXTERNAL_RESET);
  754. if (mcu & 4) SERIAL_ECHOLNPGM(STR_BROWNOUT_RESET);
  755. if (mcu & 8) SERIAL_ECHOLNPGM(STR_WATCHDOG_RESET);
  756. if (mcu & 32) SERIAL_ECHOLNPGM(STR_SOFTWARE_RESET);
  757. HAL_clear_reset_source();
  758. serialprintPGM(GET_TEXT(MSG_MARLIN));
  759. SERIAL_CHAR(' ');
  760. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  761. SERIAL_EOL();
  762. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  763. SERIAL_ECHO_MSG(
  764. STR_CONFIGURATION_VER
  765. STRING_DISTRIBUTION_DATE
  766. STR_AUTHOR STRING_CONFIG_H_AUTHOR
  767. );
  768. SERIAL_ECHO_MSG("Compiled: " __DATE__);
  769. #endif
  770. SERIAL_ECHO_START();
  771. SERIAL_ECHOLNPAIR(STR_FREE_MEMORY, freeMemory(), STR_PLANNER_BUFFER_BYTES, (int)sizeof(block_t) * (BLOCK_BUFFER_SIZE));
  772. // Set up LEDs early
  773. #if HAS_COLOR_LEDS
  774. SETUP_RUN(leds.setup());
  775. #endif
  776. #if ENABLED(USE_CONTROLLER_FAN) // Set up fan controller to initialize also the default configurations.
  777. SETUP_RUN(controllerFan.setup());
  778. #endif
  779. // UI must be initialized before EEPROM
  780. // (because EEPROM code calls the UI).
  781. SETUP_RUN(ui.init());
  782. SETUP_RUN(ui.reset_status()); // Load welcome message early. (Retained if no errors exist.)
  783. #if BOTH(HAS_SPI_LCD, SHOW_BOOTSCREEN)
  784. SETUP_RUN(ui.show_bootscreen());
  785. #endif
  786. #if BOTH(SDSUPPORT, SDCARD_EEPROM_EMULATION)
  787. SETUP_RUN(card.mount()); // Mount media with settings before first_load
  788. #endif
  789. SETUP_RUN(settings.first_load()); // Load data from EEPROM if available (or use defaults)
  790. // This also updates variables in the planner, elsewhere
  791. #if HAS_SERVICE_INTERVALS
  792. SETUP_RUN(ui.reset_status(true)); // Show service messages or keep current status
  793. #endif
  794. #if ENABLED(TOUCH_BUTTONS)
  795. SETUP_RUN(touch.init());
  796. #endif
  797. TERN_(HAS_M206_COMMAND, current_position += home_offset); // Init current position based on home_offset
  798. sync_plan_position(); // Vital to init stepper/planner equivalent for current_position
  799. SETUP_RUN(thermalManager.init()); // Initialize temperature loop
  800. SETUP_RUN(print_job_timer.init()); // Initial setup of print job timer
  801. SETUP_RUN(endstops.init()); // Init endstops and pullups
  802. SETUP_RUN(stepper.init()); // Init stepper. This enables interrupts!
  803. #if HAS_SERVOS
  804. SETUP_RUN(servo_init());
  805. #endif
  806. #if HAS_Z_SERVO_PROBE
  807. SETUP_RUN(probe.servo_probe_init());
  808. #endif
  809. #if HAS_PHOTOGRAPH
  810. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  811. #endif
  812. #if HAS_CUTTER
  813. SETUP_RUN(cutter.init());
  814. #endif
  815. #if ENABLED(COOLANT_MIST)
  816. OUT_WRITE(COOLANT_MIST_PIN, COOLANT_MIST_INVERT); // Init Mist Coolant OFF
  817. #endif
  818. #if ENABLED(COOLANT_FLOOD)
  819. OUT_WRITE(COOLANT_FLOOD_PIN, COOLANT_FLOOD_INVERT); // Init Flood Coolant OFF
  820. #endif
  821. #if HAS_BED_PROBE
  822. SETUP_RUN(endstops.enable_z_probe(false));
  823. #endif
  824. #if HAS_STEPPER_RESET
  825. SETUP_RUN(enableStepperDrivers());
  826. #endif
  827. #if HAS_I2C_DIGIPOT
  828. SETUP_RUN(digipot_i2c_init());
  829. #endif
  830. #if ENABLED(DAC_STEPPER_CURRENT)
  831. SETUP_RUN(dac_init());
  832. #endif
  833. #if EITHER(Z_PROBE_SLED, SOLENOID_PROBE) && HAS_SOLENOID_1
  834. OUT_WRITE(SOL1_PIN, LOW); // OFF
  835. #endif
  836. #if HAS_HOME
  837. SET_INPUT_PULLUP(HOME_PIN);
  838. #endif
  839. #if PIN_EXISTS(STAT_LED_RED)
  840. OUT_WRITE(STAT_LED_RED_PIN, LOW); // OFF
  841. #endif
  842. #if PIN_EXISTS(STAT_LED_BLUE)
  843. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // OFF
  844. #endif
  845. #if HAS_CASE_LIGHT
  846. #if DISABLED(CASE_LIGHT_USE_NEOPIXEL)
  847. if (PWM_PIN(CASE_LIGHT_PIN)) SET_PWM(CASE_LIGHT_PIN); else SET_OUTPUT(CASE_LIGHT_PIN);
  848. #endif
  849. SETUP_RUN(update_case_light());
  850. #endif
  851. #if ENABLED(MK2_MULTIPLEXER)
  852. SETUP_LOG("MK2_MULTIPLEXER");
  853. SET_OUTPUT(E_MUX0_PIN);
  854. SET_OUTPUT(E_MUX1_PIN);
  855. SET_OUTPUT(E_MUX2_PIN);
  856. #endif
  857. #if HAS_FANMUX
  858. SETUP_RUN(fanmux_init());
  859. #endif
  860. #if ENABLED(MIXING_EXTRUDER)
  861. SETUP_RUN(mixer.init());
  862. #endif
  863. #if ENABLED(BLTOUCH)
  864. SETUP_RUN(bltouch.init(/*set_voltage=*/true));
  865. #endif
  866. #if ENABLED(I2C_POSITION_ENCODERS)
  867. SETUP_RUN(I2CPEM.init());
  868. #endif
  869. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  870. SETUP_LOG("i2c...");
  871. i2c.onReceive(i2c_on_receive);
  872. i2c.onRequest(i2c_on_request);
  873. #endif
  874. #if DO_SWITCH_EXTRUDER
  875. SETUP_RUN(move_extruder_servo(0)); // Initialize extruder servo
  876. #endif
  877. #if ENABLED(SWITCHING_NOZZLE)
  878. SETUP_LOG("SWITCHING_NOZZLE");
  879. // Initialize nozzle servo(s)
  880. #if SWITCHING_NOZZLE_TWO_SERVOS
  881. lower_nozzle(0);
  882. raise_nozzle(1);
  883. #else
  884. move_nozzle_servo(0);
  885. #endif
  886. #endif
  887. #if ENABLED(MAGNETIC_PARKING_EXTRUDER)
  888. SETUP_RUN(mpe_settings_init());
  889. #endif
  890. #if ENABLED(PARKING_EXTRUDER)
  891. SETUP_RUN(pe_solenoid_init());
  892. #endif
  893. #if ENABLED(SWITCHING_TOOLHEAD)
  894. SETUP_RUN(swt_init());
  895. #endif
  896. #if ENABLED(ELECTROMAGNETIC_SWITCHING_TOOLHEAD)
  897. SETUP_RUN(est_init());
  898. #endif
  899. #if ENABLED(USE_WATCHDOG)
  900. SETUP_RUN(watchdog_init()); // Reinit watchdog after HAL_get_reset_source call
  901. #endif
  902. #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
  903. SETUP_RUN(init_closedloop());
  904. #endif
  905. #ifdef STARTUP_COMMANDS
  906. SETUP_LOG("STARTUP_COMMANDS");
  907. queue.inject_P(PSTR(STARTUP_COMMANDS));
  908. #endif
  909. #if ENABLED(HOST_PROMPT_SUPPORT)
  910. SETUP_RUN(host_action_prompt_end());
  911. #endif
  912. #if HAS_TRINAMIC_CONFIG && DISABLED(PSU_DEFAULT_OFF)
  913. SETUP_RUN(test_tmc_connection(true, true, true, true));
  914. #endif
  915. #if ENABLED(PRUSA_MMU2)
  916. SETUP_RUN(mmu2.init());
  917. #endif
  918. #if ENABLED(MAX7219_DEBUG)
  919. SETUP_RUN(max7219.init());
  920. #endif
  921. marlin_state = MF_RUNNING;
  922. SETUP_LOG("setup() completed.");
  923. }
  924. /**
  925. * The main Marlin program loop
  926. *
  927. * - Call idle() to handle all tasks between G-code commands
  928. * Note that no G-codes from the queue can be executed during idle()
  929. * but many G-codes can be called directly anytime like macros.
  930. * - Check whether SD card auto-start is needed now.
  931. * - Check whether SD print finishing is needed now.
  932. * - Run one G-code command from the immediate or main command queue
  933. * and open up one space. Commands in the main queue may come from sd
  934. * card, host, or by direct injection. The queue will continue to fill
  935. * as long as idle() or manage_inactivity() are being called.
  936. */
  937. void loop() {
  938. do {
  939. idle();
  940. #if ENABLED(SDSUPPORT)
  941. card.checkautostart();
  942. if (card.flag.abort_sd_printing) abortSDPrinting();
  943. if (marlin_state == MF_SD_COMPLETE) finishSDPrinting();
  944. #endif
  945. queue.advance();
  946. endstops.event_handler();
  947. } while (ENABLED(__AVR__)); // Loop forever on slower (AVR) boards
  948. }