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

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