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

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