Skip to content
Snippets Groups Projects
MarlinCore.cpp 33 KiB
Newer Older
  • Learn to ignore specific revisions
  •  * Marlin 3D Printer Firmware
    
    Scott Lahteine's avatar
    Scott Lahteine committed
     * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
    
     *
     * Based on Sprinter and grbl.
    
     * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
    
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
    
     * along with this program.  If not, see <https://www.gnu.org/licenses/>.
    
     * About Marlin
     *
     * This firmware is a mashup between Sprinter and grbl.
     *  - https://github.com/kliment/Sprinter
    
     *  - https://github.com/grbl/grbl
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #include "HAL/shared/Delay.h"
    #include "HAL/shared/esp_wifi.h"
    
    #ifdef ARDUINO
      #include <pins_arduino.h>
    #endif
    #include <math.h>
    
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #include "lcd/ultralcd.h"
    
    #include "module/motion.h"
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #include "module/planner.h"
    #include "module/stepper.h"
    #include "module/endstops.h"
    
    #include "module/probe.h"
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #include "module/temperature.h"
    #include "sd/cardreader.h"
    #include "module/configuration_store.h"
    
    #include "module/printcounter.h" // PrintCounter or Stopwatch
    
    #include "feature/closedloop.h"
    
    
    #include "module/stepper/indirection.h"
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #include "libs/nozzle.h"
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #include "gcode/parser.h"
    
    #if ENABLED(TFT_LVGL_UI)
    
      #include "lvgl.h"
    
      #include "lcd/extui/lib/mks_ui/tft_lvgl_configuration.h"
      #include "lcd/extui/lib/mks_ui/draw_ui.h"
    
    #if ENABLED(DWIN_CREALITY_LCD)
      #include "lcd/dwin/dwin.h"
      #include "lcd/dwin/dwin_lcd.h"
      #include "lcd/dwin/rotary_encoder.h"
    #endif
    
    #if ENABLED(IIC_BL24CXX_EEPROM)
    
      #include "libs/BL24CXX.h"
    
    #if ENABLED(DIRECT_STEPPING)
      #include "feature/direct_stepping.h"
    #endif
    
    
    #if ENABLED(TOUCH_BUTTONS)
      #include "feature/touch/xpt2046.h"
    #endif
    
    
    #if ENABLED(HOST_ACTION_COMMANDS)
      #include "feature/host_actions.h"
    #endif
    
    
    #if USE_BEEPER
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      #include "libs/buzzer.h"
    #endif
    
    
    #if HAS_I2C_DIGIPOT
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      #include "feature/digipot/digipot.h"
    #endif
    
    
    #if ENABLED(MIXING_EXTRUDER)
      #include "feature/mixing.h"
    #endif
    
    
    #if ENABLED(MAX7219_DEBUG)
    
      #include "feature/max7219.h"
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #if HAS_COLOR_LEDS
      #include "feature/leds/leds.h"
    
    #if ENABLED(BLTOUCH)
      #include "feature/bltouch.h"
    #endif
    
    
    #if ENABLED(POLL_JOG)
      #include "feature/joystick.h"
    #endif
    
    
    #if HAS_SERVOS
    
      #include "module/servo.h"
    
    #endif
    
    #if ENABLED(DAC_STEPPER_CURRENT)
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      #include "feature/dac/stepper_dac.h"
    
    #endif
    
    #if ENABLED(EXPERIMENTAL_I2CBUS)
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      #include "feature/twibus.h"
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      TWIBus i2c;
    
    #if ENABLED(I2C_POSITION_ENCODERS)
    
      #include "feature/encoder_i2c.h"
    
    #if HAS_TRINAMIC_CONFIG && DISABLED(PSU_DEFAULT_OFF)
    
      #include "feature/tmc_util.h"
    
    #if HAS_CUTTER
      #include "feature/spindle_laser.h"
    #endif
    
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      CardReader card;
    
    #if ENABLED(G38_PROBE_TARGET)
    
      uint8_t G38_move; // = 0
      bool G38_did_trigger; // = false
    
    #if ENABLED(DELTA)
      #include "module/delta.h"
    #elif IS_SCARA
      #include "module/scara.h"
    #endif
    
    #if HAS_LEVELING
      #include "feature/bedlevel/bedlevel.h"
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #endif
    
    
    #if BOTH(ADVANCED_PAUSE_FEATURE, PAUSE_PARK_NO_STEPPER_TIMEOUT)
    
      #include "feature/pause.h"
    #endif
    
    #if ENABLED(POWER_LOSS_RECOVERY)
    
      #include "feature/powerloss.h"
    
    #if ENABLED(CANCEL_OBJECTS)
      #include "feature/cancel_object.h"
    #endif
    
    
    #if HAS_FILAMENT_SENSOR
    
      #include "feature/runout.h"
    #endif
    
    
    #if ENABLED(HOTEND_IDLE_TIMEOUT)
      #include "feature/hotend_idle.h"
    #endif
    
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #if ENABLED(TEMP_STAT_LEDS)
      #include "feature/leds/tempstat.h"
    #endif
    
    
    #if HAS_CASE_LIGHT
      #include "feature/caselight.h"
    #endif
    
    
    #if HAS_FANMUX
      #include "feature/fanmux.h"
    #endif
    
    
    #if DO_SWITCH_EXTRUDER || ANY(SWITCHING_NOZZLE, PARKING_EXTRUDER, MAGNETIC_PARKING_EXTRUDER, ELECTROMAGNETIC_SWITCHING_TOOLHEAD, SWITCHING_TOOLHEAD)
    
      #include "module/tool_change.h"
    #endif
    
    
    #if ENABLED(USE_CONTROLLER_FAN)
      #include "feature/controllerfan.h"
    #endif
    
    
    revilor's avatar
    revilor committed
    #if ENABLED(PRUSA_MMU2)
    
      #include "feature/mmu2/mmu2.h"
    
    revilor's avatar
    revilor committed
    #endif
    
    
    #if HAS_L64XX
      #include "libs/L64XX/L64XX_Marlin.h"
    
    PGMSTR(NUL_STR, "");
    PGMSTR(M112_KILL_STR, "M112 Shutdown");
    PGMSTR(G28_STR, "G28");
    PGMSTR(M21_STR, "M21");
    PGMSTR(M23_STR, "M23 %s");
    PGMSTR(M24_STR, "M24");
    PGMSTR(SP_P_STR, " P");  PGMSTR(SP_T_STR, " T");
    PGMSTR(X_STR,     "X");  PGMSTR(Y_STR,     "Y");  PGMSTR(Z_STR,     "Z");  PGMSTR(E_STR,     "E");
    PGMSTR(X_LBL,     "X:"); PGMSTR(Y_LBL,     "Y:"); PGMSTR(Z_LBL,     "Z:"); PGMSTR(E_LBL,     "E:");
    
    PGMSTR(SP_A_STR, " A");  PGMSTR(SP_B_STR, " B");  PGMSTR(SP_C_STR, " C");
    
    PGMSTR(SP_X_STR, " X");  PGMSTR(SP_Y_STR, " Y");  PGMSTR(SP_Z_STR, " Z");  PGMSTR(SP_E_STR, " E");
    PGMSTR(SP_X_LBL, " X:"); PGMSTR(SP_Y_LBL, " Y:"); PGMSTR(SP_Z_LBL, " Z:"); PGMSTR(SP_E_LBL, " E:");
    
    MarlinState marlin_state = MF_INITIALIZING;
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
    
    bool wait_for_heatup = true;
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
    
    #if HAS_RESUME_CONTINUE
    
      bool wait_for_user; // = false;
    
    
      void wait_for_user_response(millis_t ms/*=0*/, const bool no_sleep/*=false*/) {
    
        TERN(ADVANCED_PAUSE_FEATURE,,UNUSED(no_sleep));
    
        KEEPALIVE_STATE(PAUSED_FOR_USER);
        wait_for_user = true;
        if (ms) ms += millis(); // expire time
    
        while (wait_for_user && !(ms && ELAPSED(millis(), ms)))
          idle(TERN_(ADVANCED_PAUSE_FEATURE, no_sleep));
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #if PIN_EXISTS(CHDK)
      extern millis_t chdk_timeout;
    
    #endif
    
    #if ENABLED(I2C_POSITION_ENCODERS)
      I2CPositionEncodersMgr I2CPEM;
    #endif
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    /**
    
     * ***************************************************************************
     * ******************************** FUNCTIONS ********************************
     * ***************************************************************************
    
    void setup_killpin() {
      #if HAS_KILL
    
        #if KILL_PIN_STATE
          SET_INPUT_PULLDOWN(KILL_PIN);
        #else
          SET_INPUT_PULLUP(KILL_PIN);
        #endif
    
      #endif
    
    void setup_powerhold() {
      #if HAS_SUICIDE
    
        OUT_WRITE(SUICIDE_PIN, !SUICIDE_PIN_INVERTING);
    
    AnHardt's avatar
    AnHardt committed
      #endif
    
      #if ENABLED(PSU_CONTROL)
    
        powersupply_on = ENABLED(PSU_DEFAULT_OFF);
        if (ENABLED(PSU_DEFAULT_OFF)) PSU_OFF(); else PSU_ON();
    
    /**
     * Stepper Reset (RigidBoard, et.al.)
     */
    #if HAS_STEPPER_RESET
    
      void disableStepperDrivers() { OUT_WRITE(STEPPER_RESET_PIN, LOW); } // Drive down to keep motor driver chips in reset
      void enableStepperDrivers()  { SET_INPUT(STEPPER_RESET_PIN); }      // Set to input, allowing pullups to pull the pin high
    
    #endif
    
    #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
    
      void i2c_on_receive(int bytes) { // just echo all bytes received to serial
        i2c.receive(bytes);
      }
    
      void i2c_on_request() {          // just send dummy data for now
        i2c.reply("Hello World!\n");
      }
    
    #endif
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    /**
     * Sensitive pin test for M42, M226
     */
    
    
    #include "pins/sensitive_pins.h"
    
    
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wnarrowing"
    
    
    bool pin_is_protected(const pin_t pin) {
      static const pin_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
    
      LOOP_L_N(i, COUNT(sensitive_pins)) {
    
        pin_t sensitive_pin;
        memcpy_P(&sensitive_pin, &sensitive_pins[i], sizeof(pin_t));
        if (pin == sensitive_pin) return true;
      }
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      return false;
    }
    
    #pragma GCC diagnostic pop
    
    
    void protected_pin_err() {
    
      SERIAL_ERROR_MSG(STR_ERR_PROTECTED_PIN);
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    void quickstop_stepper() {
    
      planner.quick_stop();
    
      planner.synchronize();
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      set_current_from_steppers_for_axis(ALL_AXES);
    
      sync_plan_position();
    
    Stanley's avatar
    Stanley committed
    
    
    void enable_e_steppers() {
    
      #define _ENA_E(N) ENABLE_AXIS_E##N();
    
      REPEAT(E_STEPPERS, _ENA_E)
    
    void enable_all_steppers() {
    
      TERN_(AUTO_POWER_CONTROL, powerManager.power_on());
    
      ENABLE_AXIS_X();
      ENABLE_AXIS_Y();
      ENABLE_AXIS_Z();
    
      enable_e_steppers();
    
    void disable_e_steppers() {
    
      #define _DIS_E(N) DISABLE_AXIS_E##N();
    
      REPEAT(E_STEPPERS, _DIS_E)
    
    void disable_e_stepper(const uint8_t e) {
    
      #define _CASE_DIS_E(N) case N: DISABLE_AXIS_E##N(); break;
    
        REPEAT(EXTRUDERS, _CASE_DIS_E)
    
    void disable_all_steppers() {
    
      DISABLE_AXIS_X();
      DISABLE_AXIS_Y();
      DISABLE_AXIS_Z();
    
      disable_e_steppers();
    }
    
    
    #if ENABLED(G29_RETRY_AND_RECOVER)
    
      void event_probe_failure() {
    
        #ifdef ACTION_ON_G29_FAILURE
          host_action(PSTR(ACTION_ON_G29_FAILURE));
        #endif
    
        #ifdef G29_FAILURE_COMMANDS
    
          gcode.process_subcommands_now_P(PSTR(G29_FAILURE_COMMANDS));
    
        #endif
        #if ENABLED(G29_HALT_ON_FAILURE)
          #ifdef ACTION_ON_CANCEL
            host_action_cancel();
          #endif
    
          kill(GET_TEXT(MSG_LCD_PROBING_FAILED));
    
      void event_probe_recover() {
    
        TERN_(HOST_PROMPT_SUPPORT, host_prompt_do(PROMPT_INFO, PSTR("G29 Retrying"), DISMISS_STR));
    
        #ifdef ACTION_ON_G29_RECOVER
          host_action(PSTR(ACTION_ON_G29_RECOVER));
        #endif
    
        #ifdef G29_RECOVER_COMMANDS
          gcode.process_subcommands_now_P(PSTR(G29_RECOVER_COMMANDS));
        #endif
    
    #if ENABLED(ADVANCED_PAUSE_FEATURE)
      #include "feature/pause.h"
    #else
      constexpr bool did_pause_print = false;
    #endif
    
    
    /**
     * A Print Job exists when the timer is running or SD printing
     */
    bool printJobOngoing() {
      return print_job_timer.isRunning() || IS_SD_PRINTING();
    }
    
    
    /**
     * Printing is active when the print job timer is running
     */
    bool printingIsActive() {
    
      return !did_pause_print && (print_job_timer.isRunning() || IS_SD_PRINTING());
    
    }
    
    /**
     * Printing is paused according to SD or host indicators
     */
    bool printingIsPaused() {
    
      return did_pause_print || print_job_timer.isPaused() || IS_SD_PAUSED();
    }
    
    void startOrResumeJob() {
    
      if (!printingIsPaused()) {
    
        TERN_(CANCEL_OBJECTS, cancelable.reset());
        TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator = 0);
    
        #if BOTH(LCD_SET_PROGRESS_MANUALLY, USE_M73_REMAINING_TIME)
    
          ui.reset_remaining_time();
        #endif
    
      print_job_timer.start();
    
    Scott Lahteine's avatar
    Scott Lahteine committed
    #if ENABLED(SDSUPPORT)
    
    
      inline void abortSDPrinting() {
    
        card.endFilePrint(TERN_(SD_RESORT, true));
    
    Scott Lahteine's avatar
    Scott Lahteine committed
        queue.clear();
        quickstop_stepper();
        print_job_timer.stop();
        #if DISABLED(SD_ABORT_NO_COOLDOWN)
          thermalManager.disable_all_heaters();
    
        #if !HAS_CUTTER
          thermalManager.zero_fan_speeds();
        #else
          cutter.kill();              // Full cutter shutdown including ISR control
        #endif
    
    Scott Lahteine's avatar
    Scott Lahteine committed
        wait_for_heatup = false;
    
        TERN_(POWER_LOSS_RECOVERY, recovery.purge());
    
    Scott Lahteine's avatar
    Scott Lahteine committed
        #ifdef EVENT_GCODE_SD_STOP
          queue.inject_P(PSTR(EVENT_GCODE_SD_STOP));
        #endif
      }
    
    
      inline void finishSDPrinting() {
    
        if (queue.enqueue_one_P(PSTR("M1001")))
          marlin_state = MF_RUNNING;
    
     * Minimal management of Marlin's core activities:
    
    Scott Lahteine's avatar
    Scott Lahteine committed
     *  - Keep the command buffer full
     *  - Check for maximum inactive time between commands
     *  - Check for maximum inactive time between stepper commands
    
    Scott Lahteine's avatar
    Scott Lahteine committed
     *  - Check if CHDK_PIN needs to go LOW
    
    Scott Lahteine's avatar
    Scott Lahteine committed
     *  - Check for KILL button held down
     *  - Check for HOME button held down
     *  - Check if cooling fan needs to be switched on
     *  - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
    
     *  - Pulse FET_SAFETY_PIN if it exists
    
    inline void manage_inactivity(const bool ignore_stepper_queue=false) {
    
      if (queue.length < BUFSIZE) queue.get_available_commands();
    
      const millis_t ms = millis();
    
      // Prevent steppers timing-out in the middle of M600
    
      // unless PAUSE_PARK_NO_STEPPER_TIMEOUT is disabled
      const bool parked_or_ignoring = ignore_stepper_queue ||
         (BOTH(ADVANCED_PAUSE_FEATURE, PAUSE_PARK_NO_STEPPER_TIMEOUT) && did_pause_print);
    
      // Reset both the M18/M84 activity timeout and the M85 max 'kill' timeout
      if (parked_or_ignoring) gcode.reset_stepper_timeout(ms);
    
    
      if (gcode.stepper_max_timed_out(ms)) {
    
        SERIAL_ERROR_START();
    
        SERIAL_ECHOLNPAIR(STR_KILL_INACTIVE_TIME, parser.command_ptr);
    
      // M18 / M94 : Handle steppers inactive time timeout
    
      if (gcode.stepper_inactive_time) {
    
        static bool already_shutdown_steppers; // = false
    
    
        // Any moves in the planner? Resets both the M18/M84
        // activity timeout and the M85 max 'kill' timeout
    
        if (planner.has_blocks_queued())
    
          gcode.reset_stepper_timeout(ms);
    
        else if (!parked_or_ignoring && gcode.stepper_inactive_timeout()) {
    
          if (!already_shutdown_steppers) {
            already_shutdown_steppers = true;  // L6470 SPI will consume 99% of free time without this
    
    
            // Individual axes will be disabled if configured
    
            if (ENABLED(DISABLE_INACTIVE_X)) DISABLE_AXIS_X();
            if (ENABLED(DISABLE_INACTIVE_Y)) DISABLE_AXIS_Y();
            if (ENABLED(DISABLE_INACTIVE_Z)) DISABLE_AXIS_Z();
            if (ENABLED(DISABLE_INACTIVE_E)) disable_e_steppers();
    
            TERN_(AUTO_BED_LEVELING_UBL, ubl.steppers_were_disabled());
    
        else
          already_shutdown_steppers = false;
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      #if PIN_EXISTS(CHDK) // Check if pin should be set to LOW (after M240 set it HIGH)
    
        if (chdk_timeout && ELAPSED(ms, chdk_timeout)) {
          chdk_timeout = 0;
    
    Scott Lahteine's avatar
    Scott Lahteine committed
          WRITE(CHDK_PIN, LOW);
    
    blddk's avatar
    blddk committed
        }
      #endif
    
    
      #if HAS_KILL
    
        // Check if the kill button was pressed and wait just in case it was an accidental
        // key kill key press
        // -------------------------------------------------------------------------------
    
        static int killCount = 0;   // make the inactivity button a bit less responsive
        const int KILL_DELAY = 750;
    
        if (kill_state())
    
        else if (killCount > 0)
    
        // Exceeded threshold and we can confirm that it was not accidental
        // KILL the machine
        // ----------------------------------------------------------------
    
        if (killCount >= KILL_DELAY) {
    
          SERIAL_ERROR_MSG(STR_KILL_BUTTON);
    
      #if HAS_HOME
    
        // Handle a standalone HOME button
        constexpr millis_t HOME_DEBOUNCE_DELAY = 1000UL;
        static millis_t next_home_key_ms; // = 0
        if (!IS_SD_PRINTING() && !READ(HOME_PIN)) { // HOME_PIN goes LOW when pressed
          const millis_t ms = millis();
          if (ELAPSED(ms, next_home_key_ms)) {
            next_home_key_ms = ms + HOME_DEBOUNCE_DELAY;
    
    fmalpartida's avatar
    fmalpartida committed
            LCD_MESSAGEPGM(MSG_AUTO_HOME);
    
    Scott Lahteine's avatar
    Scott Lahteine committed
            queue.enqueue_now_P(G28_STR);
    
      TERN_(USE_CONTROLLER_FAN, controllerFan.update()); // Check if fan should be turned on to cool stepper drivers down
    
      TERN_(AUTO_POWER_CONTROL, powerManager.check());
    
      TERN_(HOTEND_IDLE_TIMEOUT, hotend_idle.check());
    
    
      #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
    
        if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP
    
          && ELAPSED(ms, gcode.previous_move_ms + SEC_TO_MS(EXTRUDER_RUNOUT_SECONDS))
    
          && !planner.has_blocks_queued()
    
          #if ENABLED(SWITCHING_EXTRUDER)
    
            bool oldstatus;
            switch (active_extruder) {
    
              default: oldstatus = E0_ENABLE_READ(); ENABLE_AXIS_E0(); break;
    
              #if E_STEPPERS > 1
    
                case 2: case 3: oldstatus = E1_ENABLE_READ(); ENABLE_AXIS_E1(); break;
    
                #if E_STEPPERS > 2
    
                  case 4: case 5: oldstatus = E2_ENABLE_READ(); ENABLE_AXIS_E2(); break;
    
    Scott Lahteine's avatar
    Scott Lahteine committed
                  #if E_STEPPERS > 3
                    case 6: case 7: oldstatus = E3_ENABLE_READ(); ENABLE_AXIS_E3(); break;
                  #endif // E_STEPPERS > 3
    
                #endif // E_STEPPERS > 2
              #endif // E_STEPPERS > 1
            }
    
          #else // !SWITCHING_EXTRUDER
    
            switch (active_extruder) {
    
              #define _CASE_EN(N) case N: oldstatus = E##N##_ENABLE_READ(); ENABLE_AXIS_E##N(); break;
    
              REPEAT(E_STEPPERS, _CASE_EN);
    
          const float olde = current_position.e;
          current_position.e += EXTRUDER_RUNOUT_EXTRUDE;
          line_to_current_position(MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED));
          current_position.e = olde;
    
          planner.set_e_position_mm(olde);
    
          planner.synchronize();
    
          #if ENABLED(SWITCHING_EXTRUDER)
    
            switch (active_extruder) {
              default: oldstatus = E0_ENABLE_WRITE(oldstatus); break;
              #if E_STEPPERS > 1
                case 2: case 3: oldstatus = E1_ENABLE_WRITE(oldstatus); break;
                #if E_STEPPERS > 2
    
                  case 4: case 5: oldstatus = E2_ENABLE_WRITE(oldstatus); break;
    
                #endif // E_STEPPERS > 2
              #endif // E_STEPPERS > 1
            }
          #else // !SWITCHING_EXTRUDER
    
            switch (active_extruder) {
    
              #define _CASE_RESTORE(N) case N: E##N##_ENABLE_WRITE(oldstatus); break;
              REPEAT(E_STEPPERS, _CASE_RESTORE);
    
            }
          #endif // !SWITCHING_EXTRUDER
    
          gcode.reset_stepper_timeout(ms);
    
      #endif // EXTRUDER_RUNOUT_PREVENT
    
      #if ENABLED(DUAL_X_CARRIAGE)
    
        // handle delayed move timeout
    
        if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
    
          // travel moves have been received so enact them
          delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
    
          destination = current_position;
    
          prepare_line_to_destination();
    
      TERN_(TEMP_STAT_LEDS, handle_status_leds());
    
      TERN_(MONITOR_DRIVER_STATUS, monitor_tmc_drivers());
    
      TERN_(MONITOR_L6470_DRIVER_STATUS, L64xxManager.monitor_driver());
    
      // Limit check_axes_activity frequency to 10Hz
      static millis_t next_check_axes_ms = 0;
      if (ELAPSED(ms, next_check_axes_ms)) {
        planner.check_axes_activity();
        next_check_axes_ms = ms + 100UL;
      }
    
    
      #if PIN_EXISTS(FET_SAFETY)
        static millis_t FET_next;
        if (ELAPSED(ms, FET_next)) {
    
          FET_next = ms + FET_SAFETY_DELAY;  // 2µs pulse every FET_SAFETY_DELAY mS
    
          OUT_WRITE(FET_SAFETY_PIN, !FET_SAFETY_INVERTED);
          DELAY_US(2);
          WRITE(FET_SAFETY_PIN, FET_SAFETY_INVERTED);
        }
      #endif
    
     * Standard idle routine keeps the machine alive:
     *  - Core Marlin activities
     *  - Manage heaters (and Watchdog)
     *  - Max7219 heartbeat, animation, etc.
     *
     *  Only after setup() is complete:
     *  - Handle filament runout sensors
     *  - Run HAL idle tasks
     *  - Handle Power-Loss Recovery
     *  - Run StallGuard endstop checks
     *  - Handle SD Card insert / remove
     *  - Handle USB Flash Drive insert / remove
     *  - Announce Host Keepalive state (if any)
     *  - Update the Print Job Timer state
     *  - Update the Beeper queue
     *  - Read Buttons and Update the LCD
     *  - Run i2c Position Encoders
     *  - Auto-report Temperatures / SD Status
     *  - Update the Prusa MMU2
     *  - Handle Joystick jogging
    
    void idle(TERN_(ADVANCED_PAUSE_FEATURE, bool no_stepper_sleep/*=false*/)) {
    
    
      // Core Marlin activities
      manage_inactivity(TERN_(ADVANCED_PAUSE_FEATURE, no_stepper_sleep));
    
      // Manage Heaters (and Watchdog)
      thermalManager.manage_heater();
    
      // Max7219 heartbeat, animation, etc
    
      TERN_(MAX7219_DEBUG, max7219.idle_tasks());
    
    
      // Return if setup() isn't completed
      if (marlin_state == MF_INITIALIZING) return;
    
      // Handle filament runout sensors
    
      TERN_(HAS_FILAMENT_SENSOR, runout.run());
    
    
      // Run HAL idle tasks
      #ifdef HAL_IDLETASK
        HAL_idletask();
      #endif
    
    
      // Handle Power-Loss Recovery
    
      #if ENABLED(POWER_LOSS_RECOVERY) && PIN_EXISTS(POWER_LOSS)
    
        if (printJobOngoing()) recovery.outage();
    
      // Run StallGuard endstop checks
    
      #if ENABLED(SPI_ENDSTOPS)
    
        if (endstops.tmc_spi_homing.any
    
          && TERN1(IMPROVE_HOMING_RELIABILITY, ELAPSED(millis(), sg_guard_period))
        ) LOOP_L_N(i, 4) // Read SGT 4 times per idle loop
    
            if (endstops.tmc_spi_homing_check()) break;
      #endif
    
    
      // Handle SD Card insert / remove
    
      TERN_(SDSUPPORT, card.manage_media());
    
      // Handle USB Flash Drive insert / remove
    
      TERN_(USB_FLASH_DRIVE_SUPPORT, Sd2Card::idle());
    
      // Announce Host Keepalive state (if any)
    
      TERN_(HOST_KEEPALIVE_FEATURE, gcode.host_keepalive());
    
      // Update the Print Job Timer state
    
      TERN_(PRINTCOUNTER, print_job_timer.tick());
    
      // Update the Beeper queue
    
      TERN_(USE_BEEPER, buzzer.tick());
    
      // Handle UI input / draw events
      TERN(DWIN_CREALITY_LCD, DWIN_Update(), ui.update());
    
      // Run i2c Position Encoders
    
      #if ENABLED(I2C_POSITION_ENCODERS)
    
        static millis_t i2cpem_next_update_ms;
    
        if (planner.has_blocks_queued()) {
          const millis_t ms = millis();
          if (ELAPSED(ms, i2cpem_next_update_ms)) {
            I2CPEM.update();
            i2cpem_next_update_ms = ms + I2CPE_MIN_UPD_TIME_MS;
          }
    
      // Auto-report Temperatures / SD Status
    
        if (!gcode.autoreport_paused) {
    
          TERN_(AUTO_REPORT_TEMPERATURES, thermalManager.auto_report_temperatures());
          TERN_(AUTO_REPORT_SD_STATUS, card.auto_report_sd_status());
    
      // Update the Prusa MMU2
    
      TERN_(PRUSA_MMU2, mmu2.mmu_loop());
    
      // Handle Joystick jogging
    
      TERN_(POLL_JOG, joystick.inject_jog_moves());
    
    
      // Direct Stepping
      TERN_(DIRECT_STEPPING, page_manager.write_responses());
    
      #if ENABLED(TFT_LVGL_UI)
    
        LV_TASK_HANDLER();
      #endif
    
    }
    
    /**
     * Kill all activity and lock the machine.
     * After this the machine will need to be reset.
     */
    
    void kill(PGM_P const lcd_error/*=nullptr*/, PGM_P const lcd_component/*=nullptr*/, const bool steppers_off/*=false*/) {
    
    rafaljot's avatar
    rafaljot committed
      thermalManager.disable_all_heaters();
    
      TERN_(HAS_CUTTER, cutter.kill()); // Full cutter shutdown including ISR control
    
      SERIAL_ERROR_MSG(STR_ERR_KILLED);
    
      #if HAS_DISPLAY
    
        ui.kill_screen(lcd_error ?: GET_TEXT(MSG_KILLED), lcd_component ?: NUL_STR);
    
        UNUSED(lcd_error);
        UNUSED(lcd_component);
    
      #ifdef ACTION_ON_KILL
    
        host_action_kill();
    
    Ben Lye's avatar
    Ben Lye committed
      #endif
    
      minkill(steppers_off);
    
    void minkill(const bool steppers_off/*=false*/) {
    
      // Wait a short time (allows messages to get out before shutting down.
    
      for (int i = 1000; i--;) DELAY_US(600);
    
    
      cli(); // Stop interrupts
    
      // Wait to ensure all interrupts stopped
    
      for (int i = 1000; i--;) DELAY_US(250);
    
      // Reiterate heaters off
      thermalManager.disable_all_heaters();
    
    
      TERN_(HAS_CUTTER, cutter.kill());  // Reiterate cutter shutdown
    
      // Power off all steppers (for M112) or just the E steppers
      steppers_off ? disable_all_steppers() : disable_e_steppers();
    
      TERN_(PSU_CONTROL, PSU_OFF());
    
      TERN_(HAS_SUICIDE, suicide());
    
      #if HAS_KILL
    
        // Wait for kill to be released
    
        while (kill_state()) watchdog_refresh();
    
    
        // Wait for kill to be pressed
    
        while (!kill_state()) watchdog_refresh();
    
        void (*resetFunc)() = 0;      // Declare resetFunc() at address 0
    
    Scott Lahteine's avatar
    Scott Lahteine committed
        resetFunc();                  // Jump to address 0
    
        for (;;) watchdog_refresh();  // Wait for reset
    
    /**
     * Turn off heaters and stop the print in progress
     * After a stop the machine may be resumed with M999
     */
    
    void stop() {
    
      thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
    
    
      #if ENABLED(PROBING_FANS_OFF)
    
        if (thermalManager.fans_paused) thermalManager.set_fans_paused(false); // put things back the way they were
    
        SERIAL_ERROR_MSG(STR_ERR_STOPPED);
    
        LCD_MESSAGEPGM(MSG_STOPPED);
    
        safe_delay(350);       // allow enough time for messages to get out before stopping
    
        marlin_state = MF_STOPPED;
    
    /**
     * Marlin entry-point: Set up before the program loop
     *  - Set up the kill pin, filament runout, power hold
     *  - Start the serial port
     *  - Print startup messages and diagnostics
     *  - Get EEPROM or default settings
     *  - Initialize managers for:
     *    • temperature
     *    • planner
     *    • watchdog
     *    • stepper
     *    • photo pin
     *    • servos
     *    • LCD controller
     *    • Digipot I2C
     *    • Z probe sled
     *    • status LEDs
    
    Scott Lahteine's avatar
    Scott Lahteine committed
     *    • Max7219
    
      #if ENABLED(MARLIN_DEV_MODE)
        auto log_current_ms = [&](PGM_P const msg) {
          SERIAL_ECHO_START();
    
          SERIAL_CHAR('['); SERIAL_ECHO(millis()); SERIAL_ECHOPGM("] ");
    
          serialprintPGM(msg);
          SERIAL_EOL();
        };
        #define SETUP_LOG(M) log_current_ms(PSTR(M))
      #else
        #define SETUP_LOG(...) NOOP
      #endif
      #define SETUP_RUN(C) do{ SETUP_LOG(STRINGIFY(C)); C; }while(0)
    
    
      #if EITHER(DISABLE_DEBUG, DISABLE_JTAG)
    
        // Disable any hardware debug to free up pins for IO
    
        #if ENABLED(DISABLE_DEBUG) && defined(JTAGSWD_DISABLE)
    
          JTAGSWD_DISABLE();
        #elif defined(JTAG_DISABLE)
          JTAG_DISABLE();
        #else
    
          #error "DISABLE_(DEBUG|JTAG) is not supported for the selected MCU/Board."
    
      #endif
    
      #if NUM_SERIAL > 0
        MYSERIAL0.begin(BAUDRATE);
        uint32_t serial_connect_timeout = millis() + 1000UL;
        while (!MYSERIAL0 && PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
    
        #if HAS_MULTI_SERIAL
    
          MYSERIAL1.begin(BAUDRATE);
          serial_connect_timeout = millis() + 1000UL;
          while (!MYSERIAL1 && PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
    
        SERIAL_ECHO_MSG("start");
      #endif
    
      SETUP_RUN(HAL_init());
    
      #if HAS_L64XX
        SETUP_RUN(L64xxManager.init());  // Set up SPI, init drivers
      #endif
    
      #if ENABLED(SMART_EFFECTOR) && PIN_EXISTS(SMART_EFFECTOR_MOD)
        OUT_WRITE(SMART_EFFECTOR_MOD_PIN, LOW);   // Put Smart Effector into NORMAL mode
    
      #if HAS_FILAMENT_SENSOR
    
        SETUP_RUN(runout.setup());
    
      #if ENABLED(POWER_LOSS_RECOVERY)
    
        SETUP_RUN(recovery.setup());
    
      SETUP_RUN(setup_killpin());
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      #if HAS_TMC220x
    
        SETUP_RUN(tmc_serial_begin());
    
      #endif
    
      SETUP_RUN(setup_powerhold());
    
    
      #if HAS_STEPPER_RESET
    
        SETUP_RUN(disableStepperDrivers());
    
        #if DISABLED(TMC_USE_SW_SPI)
    
          SETUP_RUN(SPI.begin());
    
        SETUP_RUN(tmc_init_cs_pins());
    
      #ifdef BOARD_INIT
    
        SETUP_LOG("BOARD_INIT");
    
      SETUP_RUN(esp_wifi_init());
    
    
      // Check startup - does nothing if bootloader sets MCUSR to 0
    
      const byte mcu = HAL_get_reset_source();
    
      if (mcu & RST_POWER_ON) SERIAL_ECHOLNPGM(STR_POWERUP);
      if (mcu & RST_EXTERNAL) SERIAL_ECHOLNPGM(STR_EXTERNAL_RESET);
      if (mcu & RST_BROWN_OUT) SERIAL_ECHOLNPGM(STR_BROWNOUT_RESET);
      if (mcu & RST_WATCHDOG) SERIAL_ECHOLNPGM(STR_WATCHDOG_RESET);
      if (mcu & RST_SOFTWARE) SERIAL_ECHOLNPGM(STR_SOFTWARE_RESET);
    
    Scott Lahteine's avatar
    Scott Lahteine committed
      serialprintPGM(GET_TEXT(MSG_MARLIN));
    
      SERIAL_CHAR(' ');
      SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
    
      SERIAL_EOL();
    
      #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
    
        SERIAL_ECHO_MSG(
    
          STR_CONFIGURATION_VER
    
          STRING_DISTRIBUTION_DATE
    
          STR_AUTHOR STRING_CONFIG_H_AUTHOR
    
        SERIAL_ECHO_MSG("Compiled: " __DATE__);
    
      #endif
    
      SERIAL_ECHO_START();
    
      SERIAL_ECHOLNPAIR(STR_FREE_MEMORY, freeMemory(), STR_PLANNER_BUFFER_BYTES, (int)sizeof(block_t) * (BLOCK_BUFFER_SIZE));
    
      // Set up LEDs early
      #if HAS_COLOR_LEDS
    
        SETUP_RUN(leds.setup());
    
      #if ENABLED(USE_CONTROLLER_FAN)     // Set up fan controller to initialize also the default configurations.
        SETUP_RUN(controllerFan.setup());
      #endif
    
    
      // UI must be initialized before EEPROM
      // (because EEPROM code calls the UI).
    
    
      #if ENABLED(DWIN_CREALITY_LCD)
        delay(800);   // Required delay (since boot?)
        SERIAL_ECHOPGM("\nDWIN handshake ");
        if (DWIN_Handshake()) SERIAL_ECHOLNPGM("ok."); else SERIAL_ECHOLNPGM("error.");
        DWIN_Frame_SetDir(1); // Orientation 90°
        DWIN_UpdateLCD();     // Show bootscreen (first image)
      #else
        SETUP_RUN(ui.init());
        #if HAS_SPI_LCD && ENABLED(SHOW_BOOTSCREEN)
          SETUP_RUN(ui.show_bootscreen());
        #endif
        SETUP_RUN(ui.reset_status());     // Load welcome message early. (Retained if no errors exist.)
      #endif