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 30KB

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