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

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