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.

G29.cpp 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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 <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * G29.cpp - Auto Bed Leveling
  24. */
  25. #include "../../../inc/MarlinConfig.h"
  26. #if HAS_ABL_NOT_UBL
  27. #include "../../gcode.h"
  28. #include "../../../feature/bedlevel/bedlevel.h"
  29. #include "../../../module/motion.h"
  30. #include "../../../module/planner.h"
  31. #include "../../../module/stepper.h"
  32. #include "../../../module/probe.h"
  33. #include "../../queue.h"
  34. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  35. #include "../../../libs/least_squares_fit.h"
  36. #endif
  37. #if ABL_PLANAR
  38. #include "../../../libs/vector_3.h"
  39. #endif
  40. #include "../../../lcd/marlinui.h"
  41. #if ENABLED(EXTENSIBLE_UI)
  42. #include "../../../lcd/extui/ui_api.h"
  43. #elif ENABLED(DWIN_CREALITY_LCD)
  44. #include "../../../lcd/e3v2/creality/dwin.h"
  45. #elif ENABLED(DWIN_LCD_PROUI)
  46. #include "../../../lcd/e3v2/proui/dwin.h"
  47. #endif
  48. #if HAS_MULTI_HOTEND
  49. #include "../../../module/tool_change.h"
  50. #endif
  51. #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE)
  52. #include "../../../core/debug_out.h"
  53. #if ABL_USES_GRID
  54. #if ENABLED(PROBE_Y_FIRST)
  55. #define PR_OUTER_VAR abl.meshCount.x
  56. #define PR_OUTER_SIZE abl.grid_points.x
  57. #define PR_INNER_VAR abl.meshCount.y
  58. #define PR_INNER_SIZE abl.grid_points.y
  59. #else
  60. #define PR_OUTER_VAR abl.meshCount.y
  61. #define PR_OUTER_SIZE abl.grid_points.y
  62. #define PR_INNER_VAR abl.meshCount.x
  63. #define PR_INNER_SIZE abl.grid_points.x
  64. #endif
  65. #endif
  66. #define G29_RETURN(retry, did) do{ \
  67. if (TERN(G29_RETRY_AND_RECOVER, !retry, true)) { \
  68. TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(M_IDLE, false)); \
  69. } \
  70. if (did) { \
  71. TERN_(HAS_DWIN_E3V2_BASIC, DWIN_LevelingDone()); \
  72. TERN_(EXTENSIBLE_UI, ExtUI::onLevelingDone()); \
  73. } \
  74. return TERN_(G29_RETRY_AND_RECOVER, retry); \
  75. }while(0)
  76. // For manual probing values persist over multiple G29
  77. class G29_State {
  78. public:
  79. int verbose_level;
  80. xy_pos_t probePos;
  81. float measured_z;
  82. bool dryrun,
  83. reenable;
  84. #if HAS_MULTI_HOTEND
  85. uint8_t tool_index;
  86. #endif
  87. #if EITHER(PROBE_MANUALLY, AUTO_BED_LEVELING_LINEAR)
  88. int abl_probe_index;
  89. #endif
  90. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  91. int abl_points;
  92. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  93. static constexpr int abl_points = 3;
  94. #elif ABL_USES_GRID
  95. static constexpr int abl_points = GRID_MAX_POINTS;
  96. #endif
  97. #if ABL_USES_GRID
  98. xy_int8_t meshCount;
  99. xy_pos_t probe_position_lf,
  100. probe_position_rb;
  101. xy_float_t gridSpacing; // = { 0.0f, 0.0f }
  102. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  103. bool topography_map;
  104. xy_uint8_t grid_points;
  105. #else // Bilinear
  106. static constexpr xy_uint8_t grid_points = { GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y };
  107. #endif
  108. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  109. float Z_offset;
  110. bed_mesh_t z_values;
  111. #endif
  112. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  113. int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  114. float eqnAMatrix[(GRID_MAX_POINTS) * 3], // "A" matrix of the linear system of equations
  115. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  116. mean;
  117. #endif
  118. #endif
  119. };
  120. #if ABL_USES_GRID && EITHER(AUTO_BED_LEVELING_3POINT, AUTO_BED_LEVELING_BILINEAR)
  121. constexpr xy_uint8_t G29_State::grid_points;
  122. constexpr int G29_State::abl_points;
  123. #endif
  124. /**
  125. * G29: Detailed Z probe, probes the bed at 3 or more points.
  126. * Will fail if the printer has not been homed with G28.
  127. *
  128. * Enhanced G29 Auto Bed Leveling Probe Routine
  129. *
  130. * O Auto-level only if needed
  131. *
  132. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  133. * or alter the bed level data. Useful to check the topology
  134. * after a first run of G29.
  135. *
  136. * J Jettison current bed leveling data
  137. *
  138. * V Set the verbose level (0-4). Example: "G29 V3"
  139. *
  140. * Parameters With LINEAR leveling only:
  141. *
  142. * P Set the size of the grid that will be probed (P x P points).
  143. * Example: "G29 P4"
  144. *
  145. * X Set the X size of the grid that will be probed (X x Y points).
  146. * Example: "G29 X7 Y5"
  147. *
  148. * Y Set the Y size of the grid that will be probed (X x Y points).
  149. *
  150. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  151. * This is useful for manual bed leveling and finding flaws in the bed (to
  152. * assist with part placement).
  153. * Not supported by non-linear delta printer bed leveling.
  154. *
  155. * Parameters With LINEAR and BILINEAR leveling only:
  156. *
  157. * S Set the XY travel speed between probe points (in units/min)
  158. *
  159. * H Set bounds to a centered square H x H units in size
  160. *
  161. * -or-
  162. *
  163. * F Set the Front limit of the probing grid
  164. * B Set the Back limit of the probing grid
  165. * L Set the Left limit of the probing grid
  166. * R Set the Right limit of the probing grid
  167. *
  168. * Parameters with DEBUG_LEVELING_FEATURE only:
  169. *
  170. * C Make a totally fake grid with no actual probing.
  171. * For use in testing when no probing is possible.
  172. *
  173. * Parameters with BILINEAR leveling only:
  174. *
  175. * Z Supply an additional Z probe offset
  176. *
  177. * Extra parameters with PROBE_MANUALLY:
  178. *
  179. * To do manual probing simply repeat G29 until the procedure is complete.
  180. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  181. *
  182. * Q Query leveling and G29 state
  183. *
  184. * A Abort current leveling procedure
  185. *
  186. * Extra parameters with BILINEAR only:
  187. *
  188. * W Write a mesh point. (If G29 is idle.)
  189. * I X index for mesh point
  190. * J Y index for mesh point
  191. * X X for mesh point, overrides I
  192. * Y Y for mesh point, overrides J
  193. * Z Z for mesh point. Otherwise, raw current Z.
  194. *
  195. * Without PROBE_MANUALLY:
  196. *
  197. * E By default G29 will engage the Z probe, test the bed, then disengage.
  198. * Include "E" to engage/disengage the Z probe for each sample.
  199. * There's no extra effect if you have a fixed Z probe.
  200. */
  201. G29_TYPE GcodeSuite::G29() {
  202. DEBUG_SECTION(log_G29, "G29", DEBUGGING(LEVELING));
  203. // Leveling state is persistent when done manually with multiple G29 commands
  204. TERN_(PROBE_MANUALLY, static) G29_State abl;
  205. // Keep powered steppers from timing out
  206. reset_stepper_timeout();
  207. // Q = Query leveling and G29 state
  208. const bool seenQ = EITHER(DEBUG_LEVELING_FEATURE, PROBE_MANUALLY) && parser.seen_test('Q');
  209. // G29 Q is also available if debugging
  210. #if ENABLED(DEBUG_LEVELING_FEATURE)
  211. if (seenQ || DEBUGGING(LEVELING)) log_machine_info();
  212. if (DISABLED(PROBE_MANUALLY) && seenQ) G29_RETURN(false, false);
  213. #endif
  214. // A = Abort manual probing
  215. // C<bool> = Generate fake probe points (DEBUG_LEVELING_FEATURE)
  216. const bool seenA = TERN0(PROBE_MANUALLY, parser.seen_test('A')),
  217. no_action = seenA || seenQ,
  218. faux = ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY) ? parser.boolval('C') : no_action;
  219. // O = Don't level if leveling is already active
  220. if (!no_action && planner.leveling_active && parser.boolval('O')) {
  221. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("> Auto-level not needed, skip");
  222. G29_RETURN(false, false);
  223. }
  224. // Send 'N' to force homing before G29 (internal only)
  225. if (parser.seen_test('N'))
  226. process_subcommands_now(TERN(CAN_SET_LEVELING_AFTER_G28, F("G28L0"), FPSTR(G28_STR)));
  227. // Don't allow auto-leveling without homing first
  228. if (homing_needed_error()) G29_RETURN(false, false);
  229. // 3-point leveling gets points from the probe class
  230. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  231. vector_3 points[3];
  232. probe.get_three_points(points);
  233. #endif
  234. // Storage for ABL Linear results
  235. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  236. struct linear_fit_data lsf_results;
  237. #endif
  238. // Set and report "probing" state to host
  239. TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(M_PROBE, false));
  240. /**
  241. * On the initial G29 fetch command parameters.
  242. */
  243. if (!g29_in_progress) {
  244. #if HAS_MULTI_HOTEND
  245. abl.tool_index = active_extruder;
  246. if (active_extruder != 0) tool_change(0, true);
  247. #endif
  248. #if EITHER(PROBE_MANUALLY, AUTO_BED_LEVELING_LINEAR)
  249. abl.abl_probe_index = -1;
  250. #endif
  251. abl.reenable = planner.leveling_active;
  252. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  253. const bool seen_w = parser.seen_test('W');
  254. if (seen_w) {
  255. if (!leveling_is_valid()) {
  256. SERIAL_ERROR_MSG("No bilinear grid");
  257. G29_RETURN(false, false);
  258. }
  259. const float rz = parser.seenval('Z') ? RAW_Z_POSITION(parser.value_linear_units()) : current_position.z;
  260. if (!WITHIN(rz, -10, 10)) {
  261. SERIAL_ERROR_MSG("Bad Z value");
  262. G29_RETURN(false, false);
  263. }
  264. const float rx = RAW_X_POSITION(parser.linearval('X', NAN)),
  265. ry = RAW_Y_POSITION(parser.linearval('Y', NAN));
  266. int8_t i = parser.byteval('I', -1), j = parser.byteval('J', -1);
  267. #pragma GCC diagnostic push
  268. #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  269. if (!isnan(rx) && !isnan(ry)) {
  270. // Get nearest i / j from rx / ry
  271. i = (rx - bedlevel.grid_start.x) / bedlevel.grid_spacing.x + 0.5f;
  272. j = (ry - bedlevel.grid_start.y) / bedlevel.grid_spacing.y + 0.5f;
  273. LIMIT(i, 0, (GRID_MAX_POINTS_X) - 1);
  274. LIMIT(j, 0, (GRID_MAX_POINTS_Y) - 1);
  275. }
  276. #pragma GCC diagnostic pop
  277. if (WITHIN(i, 0, (GRID_MAX_POINTS_X) - 1) && WITHIN(j, 0, (GRID_MAX_POINTS_Y) - 1)) {
  278. set_bed_leveling_enabled(false);
  279. bedlevel.z_values[i][j] = rz;
  280. bedlevel.refresh_bed_level();
  281. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(i, j, rz));
  282. set_bed_leveling_enabled(abl.reenable);
  283. if (abl.reenable) report_current_position();
  284. }
  285. G29_RETURN(false, false);
  286. } // parser.seen_test('W')
  287. #else
  288. constexpr bool seen_w = false;
  289. #endif
  290. // Jettison bed leveling data
  291. if (!seen_w && parser.seen_test('J')) {
  292. reset_bed_level();
  293. G29_RETURN(false, false);
  294. }
  295. abl.verbose_level = parser.intval('V');
  296. if (!WITHIN(abl.verbose_level, 0, 4)) {
  297. SERIAL_ECHOLNPGM("?(V)erbose level implausible (0-4).");
  298. G29_RETURN(false, false);
  299. }
  300. abl.dryrun = parser.boolval('D') || TERN0(PROBE_MANUALLY, no_action);
  301. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  302. incremental_LSF_reset(&lsf_results);
  303. abl.topography_map = abl.verbose_level > 2 || parser.boolval('T');
  304. // X and Y specify points in each direction, overriding the default
  305. // These values may be saved with the completed mesh
  306. abl.grid_points.set(
  307. parser.byteval('X', GRID_MAX_POINTS_X),
  308. parser.byteval('Y', GRID_MAX_POINTS_Y)
  309. );
  310. if (parser.seenval('P')) abl.grid_points.x = abl.grid_points.y = parser.value_int();
  311. if (!WITHIN(abl.grid_points.x, 2, GRID_MAX_POINTS_X)) {
  312. SERIAL_ECHOLNPGM("?Probe points (X) implausible (2-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  313. G29_RETURN(false, false);
  314. }
  315. if (!WITHIN(abl.grid_points.y, 2, GRID_MAX_POINTS_Y)) {
  316. SERIAL_ECHOLNPGM("?Probe points (Y) implausible (2-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  317. G29_RETURN(false, false);
  318. }
  319. abl.abl_points = abl.grid_points.x * abl.grid_points.y;
  320. abl.mean = 0;
  321. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  322. abl.Z_offset = parser.linearval('Z');
  323. #endif
  324. #if ABL_USES_GRID
  325. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_FEEDRATE));
  326. const float x_min = probe.min_x(), x_max = probe.max_x(),
  327. y_min = probe.min_y(), y_max = probe.max_y();
  328. if (parser.seen('H')) {
  329. const int16_t size = (int16_t)parser.value_linear_units();
  330. abl.probe_position_lf.set(_MAX((X_CENTER) - size / 2, x_min), _MAX((Y_CENTER) - size / 2, y_min));
  331. abl.probe_position_rb.set(_MIN(abl.probe_position_lf.x + size, x_max), _MIN(abl.probe_position_lf.y + size, y_max));
  332. }
  333. else {
  334. abl.probe_position_lf.set(parser.linearval('L', x_min), parser.linearval('F', y_min));
  335. abl.probe_position_rb.set(parser.linearval('R', x_max), parser.linearval('B', y_max));
  336. }
  337. if (!probe.good_bounds(abl.probe_position_lf, abl.probe_position_rb)) {
  338. if (DEBUGGING(LEVELING)) {
  339. DEBUG_ECHOLNPGM("G29 L", abl.probe_position_lf.x, " R", abl.probe_position_rb.x,
  340. " F", abl.probe_position_lf.y, " B", abl.probe_position_rb.y);
  341. }
  342. SERIAL_ECHOLNPGM("? (L,R,F,B) out of bounds.");
  343. G29_RETURN(false, false);
  344. }
  345. // Probe at the points of a lattice grid
  346. abl.gridSpacing.set((abl.probe_position_rb.x - abl.probe_position_lf.x) / (abl.grid_points.x - 1),
  347. (abl.probe_position_rb.y - abl.probe_position_lf.y) / (abl.grid_points.y - 1));
  348. #endif // ABL_USES_GRID
  349. if (abl.verbose_level > 0) {
  350. SERIAL_ECHOPGM("G29 Auto Bed Leveling");
  351. if (abl.dryrun) SERIAL_ECHOPGM(" (DRYRUN)");
  352. SERIAL_EOL();
  353. }
  354. planner.synchronize();
  355. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  356. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("> 3-point Leveling");
  357. points[0].z = points[1].z = points[2].z = 0; // Probe at 3 arbitrary points
  358. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  359. TERN_(DWIN_LCD_PROUI, DWIN_LevelingStart());
  360. #endif
  361. TERN_(EXTENSIBLE_UI, ExtUI::onLevelingStart());
  362. if (!faux) {
  363. remember_feedrate_scaling_off();
  364. #if ENABLED(PREHEAT_BEFORE_LEVELING)
  365. if (!abl.dryrun) probe.preheat_for_probing(LEVELING_NOZZLE_TEMP,
  366. #if BOTH(DWIN_LCD_PROUI, HAS_HEATED_BED)
  367. HMI_data.BedLevT
  368. #else
  369. LEVELING_BED_TEMP
  370. #endif
  371. );
  372. #endif
  373. }
  374. // Position bed horizontally and Z probe vertically.
  375. #if defined(SAFE_BED_LEVELING_START_X) || defined(SAFE_BED_LEVELING_START_Y) || defined(SAFE_BED_LEVELING_START_Z) \
  376. || defined(SAFE_BED_LEVELING_START_I) || defined(SAFE_BED_LEVELING_START_J) || defined(SAFE_BED_LEVELING_START_K) \
  377. || defined(SAFE_BED_LEVELING_START_U) || defined(SAFE_BED_LEVELING_START_V) || defined(SAFE_BED_LEVELING_START_W)
  378. xyze_pos_t safe_position = current_position;
  379. #ifdef SAFE_BED_LEVELING_START_X
  380. safe_position.x = SAFE_BED_LEVELING_START_X;
  381. #endif
  382. #ifdef SAFE_BED_LEVELING_START_Y
  383. safe_position.y = SAFE_BED_LEVELING_START_Y;
  384. #endif
  385. #ifdef SAFE_BED_LEVELING_START_Z
  386. safe_position.z = SAFE_BED_LEVELING_START_Z;
  387. #endif
  388. #ifdef SAFE_BED_LEVELING_START_I
  389. safe_position.i = SAFE_BED_LEVELING_START_I;
  390. #endif
  391. #ifdef SAFE_BED_LEVELING_START_J
  392. safe_position.j = SAFE_BED_LEVELING_START_J;
  393. #endif
  394. #ifdef SAFE_BED_LEVELING_START_K
  395. safe_position.k = SAFE_BED_LEVELING_START_K;
  396. #endif
  397. #ifdef SAFE_BED_LEVELING_START_U
  398. safe_position.u = SAFE_BED_LEVELING_START_U;
  399. #endif
  400. #ifdef SAFE_BED_LEVELING_START_V
  401. safe_position.v = SAFE_BED_LEVELING_START_V;
  402. #endif
  403. #ifdef SAFE_BED_LEVELING_START_W
  404. safe_position.w = SAFE_BED_LEVELING_START_W;
  405. #endif
  406. do_blocking_move_to(safe_position);
  407. #endif
  408. // Disable auto bed leveling during G29.
  409. // Be formal so G29 can be done successively without G28.
  410. if (!no_action) set_bed_leveling_enabled(false);
  411. // Deploy certain probes before starting probing
  412. #if ENABLED(BLTOUCH)
  413. do_z_clearance(Z_CLEARANCE_DEPLOY_PROBE);
  414. #elif HAS_BED_PROBE
  415. if (probe.deploy()) { // (returns true on deploy failure)
  416. set_bed_leveling_enabled(abl.reenable);
  417. G29_RETURN(false, true);
  418. }
  419. #endif
  420. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  421. if (!abl.dryrun
  422. && (abl.gridSpacing != bedlevel.grid_spacing || abl.probe_position_lf != bedlevel.grid_start)
  423. ) {
  424. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  425. reset_bed_level();
  426. // Can't re-enable (on error) until the new grid is written
  427. abl.reenable = false;
  428. }
  429. // Pre-populate local Z values from the stored mesh
  430. TERN_(IS_KINEMATIC, COPY(abl.z_values, bedlevel.z_values));
  431. #endif // AUTO_BED_LEVELING_BILINEAR
  432. } // !g29_in_progress
  433. #if ENABLED(PROBE_MANUALLY)
  434. // For manual probing, get the next index to probe now.
  435. // On the first probe this will be incremented to 0.
  436. if (!no_action) {
  437. ++abl.abl_probe_index;
  438. g29_in_progress = true;
  439. }
  440. // Abort current G29 procedure, go back to idle state
  441. if (seenA && g29_in_progress) {
  442. SERIAL_ECHOLNPGM("Manual G29 aborted");
  443. SET_SOFT_ENDSTOP_LOOSE(false);
  444. set_bed_leveling_enabled(abl.reenable);
  445. g29_in_progress = false;
  446. TERN_(LCD_BED_LEVELING, ui.wait_for_move = false);
  447. }
  448. // Query G29 status
  449. if (abl.verbose_level || seenQ) {
  450. SERIAL_ECHOPGM("Manual G29 ");
  451. if (g29_in_progress)
  452. SERIAL_ECHOLNPGM("point ", _MIN(abl.abl_probe_index + 1, abl.abl_points), " of ", abl.abl_points);
  453. else
  454. SERIAL_ECHOLNPGM("idle");
  455. }
  456. // For 'A' or 'Q' exit with success state
  457. if (no_action) G29_RETURN(false, true);
  458. if (abl.abl_probe_index == 0) {
  459. // For the initial G29 S2 save software endstop state
  460. SET_SOFT_ENDSTOP_LOOSE(true);
  461. // Move close to the bed before the first point
  462. do_blocking_move_to_z(0);
  463. }
  464. else {
  465. #if EITHER(AUTO_BED_LEVELING_LINEAR, AUTO_BED_LEVELING_3POINT)
  466. const uint16_t index = abl.abl_probe_index - 1;
  467. #endif
  468. // For G29 after adjusting Z.
  469. // Save the previous Z before going to the next point
  470. abl.measured_z = current_position.z;
  471. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  472. abl.mean += abl.measured_z;
  473. abl.eqnBVector[index] = abl.measured_z;
  474. abl.eqnAMatrix[index + 0 * abl.abl_points] = abl.probePos.x;
  475. abl.eqnAMatrix[index + 1 * abl.abl_points] = abl.probePos.y;
  476. abl.eqnAMatrix[index + 2 * abl.abl_points] = 1;
  477. incremental_LSF(&lsf_results, abl.probePos, abl.measured_z);
  478. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  479. points[index].z = abl.measured_z;
  480. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  481. const float newz = abl.measured_z + abl.Z_offset;
  482. abl.z_values[abl.meshCount.x][abl.meshCount.y] = newz;
  483. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(abl.meshCount, newz));
  484. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM_P(PSTR("Save X"), abl.meshCount.x, SP_Y_STR, abl.meshCount.y, SP_Z_STR, abl.measured_z + abl.Z_offset);
  485. #endif
  486. }
  487. //
  488. // If there's another point to sample, move there with optional lift.
  489. //
  490. #if ABL_USES_GRID
  491. // Skip any unreachable points
  492. while (abl.abl_probe_index < abl.abl_points) {
  493. // Set abl.meshCount.x, abl.meshCount.y based on abl.abl_probe_index, with zig-zag
  494. PR_OUTER_VAR = abl.abl_probe_index / PR_INNER_SIZE;
  495. PR_INNER_VAR = abl.abl_probe_index - (PR_OUTER_VAR * PR_INNER_SIZE);
  496. // Probe in reverse order for every other row/column
  497. const bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_SIZE) & 1);
  498. if (zig) PR_INNER_VAR = (PR_INNER_SIZE - 1) - PR_INNER_VAR;
  499. abl.probePos = abl.probe_position_lf + abl.gridSpacing * abl.meshCount.asFloat();
  500. TERN_(AUTO_BED_LEVELING_LINEAR, abl.indexIntoAB[abl.meshCount.x][abl.meshCount.y] = abl.abl_probe_index);
  501. // Keep looping till a reachable point is found
  502. if (position_is_reachable(abl.probePos)) break;
  503. ++abl.abl_probe_index;
  504. }
  505. // Is there a next point to move to?
  506. if (abl.abl_probe_index < abl.abl_points) {
  507. _manual_goto_xy(abl.probePos); // Can be used here too!
  508. // Disable software endstops to allow manual adjustment
  509. // If G29 is not completed, they will not be re-enabled
  510. SET_SOFT_ENDSTOP_LOOSE(true);
  511. G29_RETURN(false, true);
  512. }
  513. else {
  514. // Leveling done! Fall through to G29 finishing code below
  515. SERIAL_ECHOLNPGM("Grid probing done.");
  516. // Re-enable software endstops, if needed
  517. SET_SOFT_ENDSTOP_LOOSE(false);
  518. }
  519. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  520. // Probe at 3 arbitrary points
  521. if (abl.abl_probe_index < abl.abl_points) {
  522. abl.probePos = xy_pos_t(points[abl.abl_probe_index]);
  523. _manual_goto_xy(abl.probePos);
  524. // Disable software endstops to allow manual adjustment
  525. // If G29 is not completed, they will not be re-enabled
  526. SET_SOFT_ENDSTOP_LOOSE(true);
  527. G29_RETURN(false, true);
  528. }
  529. else {
  530. SERIAL_ECHOLNPGM("3-point probing done.");
  531. // Re-enable software endstops, if needed
  532. SET_SOFT_ENDSTOP_LOOSE(false);
  533. if (!abl.dryrun) {
  534. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  535. if (planeNormal.z < 0) planeNormal *= -1;
  536. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  537. // Can't re-enable (on error) until the new grid is written
  538. abl.reenable = false;
  539. }
  540. }
  541. #endif // AUTO_BED_LEVELING_3POINT
  542. #else // !PROBE_MANUALLY
  543. {
  544. const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;
  545. abl.measured_z = 0;
  546. #if ABL_USES_GRID
  547. bool zig = PR_OUTER_SIZE & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  548. // Outer loop is X with PROBE_Y_FIRST enabled
  549. // Outer loop is Y with PROBE_Y_FIRST disabled
  550. for (PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_SIZE && !isnan(abl.measured_z); PR_OUTER_VAR++) {
  551. int8_t inStart, inStop, inInc;
  552. if (zig) { // Zig away from origin
  553. inStart = 0; // Left or front
  554. inStop = PR_INNER_SIZE; // Right or back
  555. inInc = 1; // Zig right
  556. }
  557. else { // Zag towards origin
  558. inStart = PR_INNER_SIZE - 1; // Right or back
  559. inStop = -1; // Left or front
  560. inInc = -1; // Zag left
  561. }
  562. zig ^= true; // zag
  563. // An index to print current state
  564. uint8_t pt_index = (PR_OUTER_VAR) * (PR_INNER_SIZE) + 1;
  565. // Inner loop is Y with PROBE_Y_FIRST enabled
  566. // Inner loop is X with PROBE_Y_FIRST disabled
  567. for (PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; pt_index++, PR_INNER_VAR += inInc) {
  568. abl.probePos = abl.probe_position_lf + abl.gridSpacing * abl.meshCount.asFloat();
  569. TERN_(AUTO_BED_LEVELING_LINEAR, abl.indexIntoAB[abl.meshCount.x][abl.meshCount.y] = ++abl.abl_probe_index); // 0...
  570. // Avoid probing outside the round or hexagonal area
  571. if (TERN0(IS_KINEMATIC, !probe.can_reach(abl.probePos))) continue;
  572. if (abl.verbose_level) SERIAL_ECHOLNPGM("Probing mesh point ", pt_index, "/", abl.abl_points, ".");
  573. TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT(MSG_PROBING_POINT), int(pt_index), int(abl.abl_points)));
  574. abl.measured_z = faux ? 0.001f * random(-100, 101) : probe.probe_at_point(abl.probePos, raise_after, abl.verbose_level);
  575. if (isnan(abl.measured_z)) {
  576. set_bed_leveling_enabled(abl.reenable);
  577. break; // Breaks out of both loops
  578. }
  579. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  580. abl.mean += abl.measured_z;
  581. abl.eqnBVector[abl.abl_probe_index] = abl.measured_z;
  582. abl.eqnAMatrix[abl.abl_probe_index + 0 * abl.abl_points] = abl.probePos.x;
  583. abl.eqnAMatrix[abl.abl_probe_index + 1 * abl.abl_points] = abl.probePos.y;
  584. abl.eqnAMatrix[abl.abl_probe_index + 2 * abl.abl_points] = 1;
  585. incremental_LSF(&lsf_results, abl.probePos, abl.measured_z);
  586. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  587. const float z = abl.measured_z + abl.Z_offset;
  588. abl.z_values[abl.meshCount.x][abl.meshCount.y] = z;
  589. TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(abl.meshCount, z));
  590. #endif
  591. abl.reenable = false;
  592. idle_no_sleep();
  593. } // inner
  594. } // outer
  595. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  596. // Probe at 3 arbitrary points
  597. LOOP_L_N(i, 3) {
  598. if (abl.verbose_level) SERIAL_ECHOLNPGM("Probing point ", i + 1, "/3.");
  599. TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/3"), GET_TEXT(MSG_PROBING_POINT), int(i + 1)));
  600. // Retain the last probe position
  601. abl.probePos = xy_pos_t(points[i]);
  602. abl.measured_z = faux ? 0.001 * random(-100, 101) : probe.probe_at_point(abl.probePos, raise_after, abl.verbose_level);
  603. if (isnan(abl.measured_z)) {
  604. set_bed_leveling_enabled(abl.reenable);
  605. break;
  606. }
  607. points[i].z = abl.measured_z;
  608. }
  609. if (!abl.dryrun && !isnan(abl.measured_z)) {
  610. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  611. if (planeNormal.z < 0) planeNormal *= -1;
  612. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  613. // Can't re-enable (on error) until the new grid is written
  614. abl.reenable = false;
  615. }
  616. #endif // AUTO_BED_LEVELING_3POINT
  617. TERN_(HAS_STATUS_MESSAGE, ui.reset_status());
  618. // Stow the probe. No raise for FIX_MOUNTED_PROBE.
  619. if (probe.stow()) {
  620. set_bed_leveling_enabled(abl.reenable);
  621. abl.measured_z = NAN;
  622. }
  623. }
  624. #endif // !PROBE_MANUALLY
  625. //
  626. // G29 Finishing Code
  627. //
  628. // Unless this is a dry run, auto bed leveling will
  629. // definitely be enabled after this point.
  630. //
  631. // If code above wants to continue leveling, it should
  632. // return or loop before this point.
  633. //
  634. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  635. #if ENABLED(PROBE_MANUALLY)
  636. g29_in_progress = false;
  637. TERN_(LCD_BED_LEVELING, ui.wait_for_move = false);
  638. #endif
  639. // Calculate leveling, print reports, correct the position
  640. if (!isnan(abl.measured_z)) {
  641. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  642. if (abl.dryrun)
  643. bedlevel.print_leveling_grid(&abl.z_values);
  644. else {
  645. bedlevel.set_grid(abl.gridSpacing, abl.probe_position_lf);
  646. COPY(bedlevel.z_values, abl.z_values);
  647. TERN_(IS_KINEMATIC, bedlevel.extrapolate_unprobed_bed_level());
  648. bedlevel.refresh_bed_level();
  649. bedlevel.print_leveling_grid();
  650. }
  651. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  652. // For LINEAR leveling calculate matrix, print reports, correct the position
  653. /**
  654. * solve the plane equation ax + by + d = z
  655. * A is the matrix with rows [x y 1] for all the probed points
  656. * B is the vector of the Z positions
  657. * the normal vector to the plane is formed by the coefficients of the
  658. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  659. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  660. */
  661. struct { float a, b, d; } plane_equation_coefficients;
  662. finish_incremental_LSF(&lsf_results);
  663. plane_equation_coefficients.a = -lsf_results.A; // We should be able to eliminate the '-' on these three lines and down below
  664. plane_equation_coefficients.b = -lsf_results.B; // but that is not yet tested.
  665. plane_equation_coefficients.d = -lsf_results.D;
  666. abl.mean /= abl.abl_points;
  667. if (abl.verbose_level) {
  668. SERIAL_ECHOPAIR_F("Eqn coefficients: a: ", plane_equation_coefficients.a, 8);
  669. SERIAL_ECHOPAIR_F(" b: ", plane_equation_coefficients.b, 8);
  670. SERIAL_ECHOPAIR_F(" d: ", plane_equation_coefficients.d, 8);
  671. if (abl.verbose_level > 2)
  672. SERIAL_ECHOPAIR_F("\nMean of sampled points: ", abl.mean, 8);
  673. SERIAL_EOL();
  674. }
  675. // Create the matrix but don't correct the position yet
  676. if (!abl.dryrun)
  677. planner.bed_level_matrix = matrix_3x3::create_look_at(
  678. vector_3(-plane_equation_coefficients.a, -plane_equation_coefficients.b, 1) // We can eliminate the '-' here and up above
  679. );
  680. // Show the Topography map if enabled
  681. if (abl.topography_map) {
  682. float min_diff = 999;
  683. auto print_topo_map = [&](FSTR_P const title, const bool get_min) {
  684. SERIAL_ECHOF(title);
  685. for (int8_t yy = abl.grid_points.y - 1; yy >= 0; yy--) {
  686. LOOP_L_N(xx, abl.grid_points.x) {
  687. const int ind = abl.indexIntoAB[xx][yy];
  688. xyz_float_t tmp = { abl.eqnAMatrix[ind + 0 * abl.abl_points],
  689. abl.eqnAMatrix[ind + 1 * abl.abl_points], 0 };
  690. planner.bed_level_matrix.apply_rotation_xyz(tmp.x, tmp.y, tmp.z);
  691. if (get_min) NOMORE(min_diff, abl.eqnBVector[ind] - tmp.z);
  692. const float subval = get_min ? abl.mean : tmp.z + min_diff,
  693. diff = abl.eqnBVector[ind] - subval;
  694. SERIAL_CHAR(' '); if (diff >= 0.0) SERIAL_CHAR('+'); // Include + for column alignment
  695. SERIAL_ECHO_F(diff, 5);
  696. } // xx
  697. SERIAL_EOL();
  698. } // yy
  699. SERIAL_EOL();
  700. };
  701. print_topo_map(F("\nBed Height Topography:\n"
  702. " +--- BACK --+\n"
  703. " | |\n"
  704. " L | (+) | R\n"
  705. " E | | I\n"
  706. " F | (-) N (+) | G\n"
  707. " T | | H\n"
  708. " | (-) | T\n"
  709. " | |\n"
  710. " O-- FRONT --+\n"
  711. " (0,0)\n"), true);
  712. if (abl.verbose_level > 3)
  713. print_topo_map(F("\nCorrected Bed Height vs. Bed Topology:\n"), false);
  714. } // abl.topography_map
  715. #endif // AUTO_BED_LEVELING_LINEAR
  716. #if ABL_PLANAR
  717. // For LINEAR and 3POINT leveling correct the current position
  718. if (abl.verbose_level > 0)
  719. planner.bed_level_matrix.debug(F("\n\nBed Level Correction Matrix:"));
  720. if (!abl.dryrun) {
  721. //
  722. // Correct the current XYZ position based on the tilted plane.
  723. //
  724. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  725. xyze_pos_t converted = current_position;
  726. planner.force_unapply_leveling(converted); // use conversion machinery
  727. // Use the last measured distance to the bed, if possible
  728. if ( NEAR(current_position.x, abl.probePos.x - probe.offset_xy.x)
  729. && NEAR(current_position.y, abl.probePos.y - probe.offset_xy.y)
  730. ) {
  731. const float simple_z = current_position.z - abl.measured_z;
  732. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Probed Z", simple_z, " Matrix Z", converted.z, " Discrepancy ", simple_z - converted.z);
  733. converted.z = simple_z;
  734. }
  735. // The rotated XY and corrected Z are now current_position
  736. current_position = converted;
  737. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  738. }
  739. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  740. if (!abl.dryrun) {
  741. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("G29 uncorrected Z:", current_position.z);
  742. // Unapply the offset because it is going to be immediately applied
  743. // and cause compensation movement in Z
  744. current_position.z -= bedlevel.get_z_correction(current_position)
  745. TERN_(ENABLE_LEVELING_FADE_HEIGHT, * planner.fade_scaling_factor_for_z(current_position.z));
  746. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM(" corrected Z:", current_position.z);
  747. }
  748. #endif // ABL_PLANAR
  749. // Auto Bed Leveling is complete! Enable if possible.
  750. planner.leveling_active = !abl.dryrun || abl.reenable;
  751. } // !isnan(abl.measured_z)
  752. // Restore state after probing
  753. if (!faux) restore_feedrate_and_scaling();
  754. // Sync the planner from the current_position
  755. if (planner.leveling_active) sync_plan_position();
  756. TERN_(HAS_BED_PROBE, probe.move_z_after_probing());
  757. #ifdef Z_PROBE_END_SCRIPT
  758. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  759. planner.synchronize();
  760. process_subcommands_now(F(Z_PROBE_END_SCRIPT));
  761. #endif
  762. TERN_(HAS_MULTI_HOTEND, if (abl.tool_index != 0) tool_change(abl.tool_index));
  763. report_current_position();
  764. G29_RETURN(isnan(abl.measured_z), true);
  765. }
  766. #endif // HAS_ABL_NOT_UBL