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

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