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.

ubl_G29.cpp 71KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #include "../../../inc/MarlinConfig.h"
  23. #if ENABLED(AUTO_BED_LEVELING_UBL)
  24. //#define UBL_DEVEL_DEBUGGING
  25. #include "ubl.h"
  26. #include "../../../Marlin.h"
  27. #include "../../../HAL/shared/persistent_store_api.h"
  28. #include "../../../libs/hex_print_routines.h"
  29. #include "../../../module/configuration_store.h"
  30. #include "../../../lcd/ultralcd.h"
  31. #include "../../../module/stepper.h"
  32. #include "../../../module/planner.h"
  33. #include "../../../module/probe.h"
  34. #include "../../../gcode/gcode.h"
  35. #include "../../../core/serial.h"
  36. #include "../../../gcode/parser.h"
  37. #include "../../../feature/bedlevel/bedlevel.h"
  38. #include "../../../libs/least_squares_fit.h"
  39. #if ENABLED(DUAL_X_CARRIAGE)
  40. #include "../../../module/tool_change.h"
  41. #endif
  42. #include <math.h>
  43. #define UBL_G29_P31
  44. extern float destination[XYZE], current_position[XYZE];
  45. #if HAS_LCD_MENU
  46. void _lcd_ubl_output_map_lcd();
  47. #endif
  48. #define SIZE_OF_LITTLE_RAISE 1
  49. #define BIG_RAISE_NOT_NEEDED 0
  50. int unified_bed_leveling::g29_verbose_level,
  51. unified_bed_leveling::g29_phase_value,
  52. unified_bed_leveling::g29_repetition_cnt,
  53. unified_bed_leveling::g29_storage_slot = 0,
  54. unified_bed_leveling::g29_map_type;
  55. bool unified_bed_leveling::g29_c_flag,
  56. unified_bed_leveling::g29_x_flag,
  57. unified_bed_leveling::g29_y_flag;
  58. float unified_bed_leveling::g29_x_pos,
  59. unified_bed_leveling::g29_y_pos,
  60. unified_bed_leveling::g29_card_thickness = 0,
  61. unified_bed_leveling::g29_constant = 0;
  62. #if HAS_BED_PROBE
  63. int unified_bed_leveling::g29_grid_size;
  64. #endif
  65. /**
  66. * G29: Unified Bed Leveling by Roxy
  67. *
  68. * Parameters understood by this leveling system:
  69. *
  70. * A Activate Activate the Unified Bed Leveling system.
  71. *
  72. * B # Business Use the 'Business Card' mode of the Manual Probe subsystem with P2.
  73. * Note: A non-compressible Spark Gap feeler gauge is recommended over a business card.
  74. * In this mode of G29 P2, a business or index card is used as a shim that the nozzle can
  75. * grab onto as it is lowered. In principle, the nozzle-bed distance is the same when the
  76. * same resistance is felt in the shim. You can omit the numerical value on first invocation
  77. * of G29 P2 B to measure shim thickness. Subsequent use of 'B' will apply the previously-
  78. * measured thickness by default.
  79. *
  80. * C Continue G29 P1 C continues the generation of a partially-constructed Mesh without invalidating
  81. * previous measurements.
  82. *
  83. * C G29 P2 C tells the Manual Probe subsystem to not use the current nozzle
  84. * location in its search for the closest unmeasured Mesh Point. Instead, attempt to
  85. * start at one end of the uprobed points and Continue sequentially.
  86. *
  87. * G29 P3 C specifies the Constant for the fill. Otherwise, uses a "reasonable" value.
  88. *
  89. * C Current G29 Z C uses the Current location (instead of bed center or nearest edge).
  90. *
  91. * D Disable Disable the Unified Bed Leveling system.
  92. *
  93. * E Stow_probe Stow the probe after each sampled point.
  94. *
  95. * F # Fade Fade the amount of Mesh Based Compensation over a specified height. At the
  96. * specified height, no correction is applied and natural printer kenimatics take over. If no
  97. * number is specified for the command, 10mm is assumed to be reasonable.
  98. *
  99. * H # Height With P2, 'H' specifies the Height to raise the nozzle after each manual probe of the bed.
  100. * If omitted, the nozzle will raise by Z_CLEARANCE_BETWEEN_PROBES.
  101. *
  102. * H # Offset With P4, 'H' specifies the Offset above the mesh height to place the nozzle.
  103. * If omitted, Z_CLEARANCE_BETWEEN_PROBES will be used.
  104. *
  105. * I # Invalidate Invalidate the specified number of Mesh Points near the given 'X' 'Y'. If X or Y are omitted,
  106. * the nozzle location is used. If no 'I' value is given, only the point nearest to the location
  107. * is invalidated. Use 'T' to produce a map afterward. This command is useful to invalidate a
  108. * portion of the Mesh so it can be adjusted using other UBL tools. When attempting to invalidate
  109. * an isolated bad mesh point, the 'T' option shows the nozzle position in the Mesh with (#). You
  110. * can move the nozzle around and use this feature to select the center of the area (or cell) to
  111. * invalidate.
  112. *
  113. * J # Grid Perform a Grid Based Leveling of the current Mesh using a grid with n points on a side.
  114. * Not specifying a grid size will invoke the 3-Point leveling function.
  115. *
  116. * L Load Load Mesh from the previously activated location in the EEPROM.
  117. *
  118. * L # Load Load Mesh from the specified location in the EEPROM. Set this location as activated
  119. * for subsequent Load and Store operations.
  120. *
  121. * The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will
  122. * start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with
  123. * each additional Phase that processes it.
  124. *
  125. * P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the
  126. * 3D Printer to the same state it was in before the Unified Bed Leveling Compensation
  127. * was turned on. Setting the entire Mesh to Zero is a special case that allows
  128. * a subsequent G or T leveling operation for backward compatibility.
  129. *
  130. * P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using
  131. * the Z-Probe. Usually the probe can't reach all areas that the nozzle can reach. For delta
  132. * printers only the areas where the probe and nozzle can both reach will be automatically probed.
  133. *
  134. * Unreachable points will be handled in Phase 2 and Phase 3.
  135. *
  136. * Use 'C' to leave the previous mesh intact and automatically probe needed points. This allows you
  137. * to invalidate parts of the Mesh but still use Automatic Probing.
  138. *
  139. * The 'X' and 'Y' parameters prioritize where to try and measure points. If omitted, the current
  140. * probe position is used.
  141. *
  142. * Use 'T' (Topology) to generate a report of mesh generation.
  143. *
  144. * P1 will suspend Mesh generation if the controller button is held down. Note that you may need
  145. * to press and hold the switch for several seconds if moves are underway.
  146. *
  147. * P2 Phase 2 Probe unreachable points.
  148. *
  149. * Use 'H' to set the height between Mesh points. If omitted, Z_CLEARANCE_BETWEEN_PROBES is used.
  150. * Smaller values will be quicker. Move the nozzle down till it barely touches the bed. Make sure the
  151. * nozzle is clean and unobstructed. Use caution and move slowly. This can damage your printer!
  152. * (Uses SIZE_OF_LITTLE_RAISE mm if the nozzle is moving less than BIG_RAISE_NOT_NEEDED mm.)
  153. *
  154. * The 'H' value can be negative if the Mesh dips in a large area. Press and hold the
  155. * controller button to terminate the current Phase 2 command. You can then re-issue "G29 P 2"
  156. * with an 'H' parameter more suitable for the area you're manually probing. Note that the command
  157. * tries to start in a corner of the bed where movement will be predictable. Override the distance
  158. * calculation location with the X and Y parameters. You can print a Mesh Map (G29 T) to see where
  159. * the mesh is invalidated and where the nozzle needs to move to complete the command. Use 'C' to
  160. * indicate that the search should be based on the current position.
  161. *
  162. * The 'B' parameter for this command is described above. It places the manual probe subsystem into
  163. * Business Card mode where the thickness of a business card is measured and then used to accurately
  164. * set the nozzle height in all manual probing for the duration of the command. A Business card can
  165. * be used, but you'll get better results with a flexible Shim that doesn't compress. This makes it
  166. * easier to produce similar amounts of force and get more accurate measurements. Google if you're
  167. * not sure how to use a shim.
  168. *
  169. * The 'T' (Map) parameter helps track Mesh building progress.
  170. *
  171. * NOTE: P2 requires an LCD controller!
  172. *
  173. * P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. There are two different paths to
  174. * go down:
  175. *
  176. * - If a 'C' constant is specified, the closest invalid mesh points to the nozzle will be filled,
  177. * and a repeat count can then also be specified with 'R'.
  178. *
  179. * - Leaving out 'C' invokes Smart Fill, which scans the mesh from the edges inward looking for
  180. * invalid mesh points. Adjacent points are used to determine the bed slope. If the bed is sloped
  181. * upward from the invalid point, it takes the value of the nearest point. If sloped downward, it's
  182. * replaced by a value that puts all three points in a line. This version of G29 P3 is a quick, easy
  183. * and (usually) safe way to populate unprobed mesh regions before continuing to G26 Mesh Validation
  184. * Pattern. Note that this populates the mesh with unverified values. Pay attention and use caution.
  185. *
  186. * P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assumes the existence of
  187. * an LCD Panel. It is possible to fine tune the mesh without an LCD Panel using
  188. * G42 and M421. See the UBL documentation for further details.
  189. *
  190. * Phase 4 is meant to be used with G26 Mesh Validation to fine tune the mesh by direct editing
  191. * of Mesh Points. Raise and lower points to fine tune the mesh until it gives consistently reliable
  192. * adhesion.
  193. *
  194. * P4 moves to the closest Mesh Point (and/or the given X Y), raises the nozzle above the mesh height
  195. * by the given 'H' offset (or default 0), and waits while the controller is used to adjust the nozzle
  196. * height. On click the displayed height is saved in the mesh.
  197. *
  198. * Start Phase 4 at a specific location with X and Y. Adjust a specific number of Mesh Points with
  199. * the 'R' (Repeat) parameter. (If 'R' is left out, the whole matrix is assumed.) This command can be
  200. * terminated early (e.g., after editing the area of interest) by pressing and holding the encoder button.
  201. *
  202. * The general form is G29 P4 [R points] [X position] [Y position]
  203. *
  204. * The H [offset] parameter is useful if a shim is used to fine-tune the mesh. For a 0.4mm shim the
  205. * command would be G29 P4 H0.4. The nozzle is moved to the shim height, you adjust height to the shim,
  206. * and on click the height minus the shim thickness will be saved in the mesh.
  207. *
  208. * !!Use with caution, as a very poor mesh could cause the nozzle to crash into the bed!!
  209. *
  210. * NOTE: P4 is not available unless you have LCD support enabled!
  211. *
  212. * P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and
  213. * work with the Mesh if it is Mean Adjusted. You can specify a C parameter to
  214. * Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically
  215. * execute a G29 P6 C <mean height>.
  216. *
  217. * P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified
  218. * with the C parameter. Being able to adjust the height of a Mesh is useful tool. It
  219. * can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally,
  220. * you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring
  221. * 0.000 at the Z Home location.
  222. *
  223. * Q Test Load specified Test Pattern to assist in checking correct operation of system. This
  224. * command is not anticipated to be of much value to the typical user. It is intended
  225. * for developers to help them verify correct operation of the Unified Bed Leveling System.
  226. *
  227. * R # Repeat Repeat this command the specified number of times. If no number is specified the
  228. * command will be repeated GRID_MAX_POINTS_X * GRID_MAX_POINTS_Y times.
  229. *
  230. * S Store Store the current Mesh in the Activated area of the EEPROM. It will also store the
  231. * current state of the Unified Bed Leveling system in the EEPROM.
  232. *
  233. * S # Store Store the current Mesh at the specified location in EEPROM. Activate this location
  234. * for subsequent Load and Store operations. Valid storage slot numbers begin at 0 and
  235. * extend to a limit related to the available EEPROM storage.
  236. *
  237. * S -1 Store Print the current Mesh as G-code that can be used to restore the mesh anytime.
  238. *
  239. * T Topology Display the Mesh Map Topology.
  240. * 'T' can be used alone (e.g., G29 T) or in combination with most of the other commands.
  241. * This option works with all Phase commands (e.g., G29 P4 R 5 T X 50 Y100 C -.1 O)
  242. * This parameter can also specify a Map Type. T0 (the default) is user-readable. T1 can
  243. * is suitable to paste into a spreadsheet for a 3D graph of the mesh.
  244. *
  245. * U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds.
  246. * Only used for G29 P1 T U. This speeds up the probing of the edge of the bed. Useful
  247. * when the entire bed doesn't need to be probed because it will be adjusted.
  248. *
  249. * V # Verbosity Set the verbosity level (0-4) for extra details. (Default 0)
  250. *
  251. * X # X Location for this command
  252. *
  253. * Y # Y Location for this command
  254. *
  255. * With UBL_DEVEL_DEBUGGING:
  256. *
  257. * K # Kompare Kompare current Mesh with stored Mesh #, replacing current Mesh with the result.
  258. * This command literally performs a diff between two Meshes.
  259. *
  260. * Q-1 Dump EEPROM Dump the UBL contents stored in EEPROM as HEX format. Useful for developers to help
  261. * verify correct operation of the UBL.
  262. *
  263. * W What? Display valuable UBL data.
  264. *
  265. *
  266. * Release Notes:
  267. * You MUST do M502, M500 to initialize the storage. Failure to do this will cause all
  268. * kinds of problems. Enabling EEPROM Storage is required.
  269. *
  270. * When you do a G28 and G29 P1 to automatically build your first mesh, you are going to notice that
  271. * UBL probes points increasingly further from the starting location. (The starting location defaults
  272. * to the center of the bed.) In contrast, ABL and MBL follow a zigzag pattern. The spiral pattern is
  273. * especially better for Delta printers, since it populates the center of the mesh first, allowing for
  274. * a quicker test print to verify settings. You don't need to populate the entire mesh to use it.
  275. * After all, you don't want to spend a lot of time generating a mesh only to realize the resolution
  276. * or zprobe_zoffset are incorrect. Mesh-generation gathers points starting closest to the nozzle unless
  277. * an (X,Y) coordinate pair is given.
  278. *
  279. * Unified Bed Leveling uses a lot of EEPROM storage to hold its data, and it takes some effort to get
  280. * the mesh just right. To prevent this valuable data from being destroyed as the EEPROM structure
  281. * evolves, UBL stores all mesh data at the end of EEPROM.
  282. *
  283. * UBL is founded on Edward Patel's Mesh Bed Leveling code. A big 'Thanks!' to him and the creators of
  284. * 3-Point and Grid Based leveling. Combining their contributions we now have the functionality and
  285. * features of all three systems combined.
  286. */
  287. void unified_bed_leveling::G29() {
  288. if (g29_parameter_parsing()) return; // Abort on parameter error
  289. const int8_t p_val = parser.intval('P', -1);
  290. const bool may_move = p_val == 1 || p_val == 2 || p_val == 4 || parser.seen('J');
  291. // Check for commands that require the printer to be homed
  292. if (may_move) {
  293. if (axis_unhomed_error()) gcode.home_all_axes();
  294. #if ENABLED(DUAL_X_CARRIAGE)
  295. if (active_extruder != 0) tool_change(0);
  296. #endif
  297. }
  298. // Invalidate Mesh Points. This command is a little bit asymmetrical because
  299. // it directly specifies the repetition count and does not use the 'R' parameter.
  300. if (parser.seen('I')) {
  301. uint8_t cnt = 0;
  302. g29_repetition_cnt = parser.has_value() ? parser.value_int() : 1;
  303. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  304. set_all_mesh_points_to_value(NAN);
  305. }
  306. else {
  307. while (g29_repetition_cnt--) {
  308. if (cnt > 20) { cnt = 0; idle(); }
  309. const mesh_index_pair location = find_closest_mesh_point_of_type(REAL, g29_x_pos, g29_y_pos, USE_NOZZLE_AS_REFERENCE, NULL);
  310. if (location.x_index < 0) {
  311. // No more REACHABLE mesh points to invalidate, so we ASSUME the user
  312. // meant to invalidate the ENTIRE mesh, which cannot be done with
  313. // find_closest_mesh_point loop which only returns REACHABLE points.
  314. set_all_mesh_points_to_value(NAN);
  315. SERIAL_ECHOLNPGM("Entire Mesh invalidated.\n");
  316. break; // No more invalid Mesh Points to populate
  317. }
  318. z_values[location.x_index][location.y_index] = NAN;
  319. cnt++;
  320. }
  321. }
  322. SERIAL_ECHOLNPGM("Locations invalidated.\n");
  323. }
  324. if (parser.seen('Q')) {
  325. const int test_pattern = parser.has_value() ? parser.value_int() : -99;
  326. if (!WITHIN(test_pattern, -1, 2)) {
  327. SERIAL_ECHOLNPGM("Invalid test_pattern value. (-1 to 2)\n");
  328. return;
  329. }
  330. SERIAL_ECHOLNPGM("Loading test_pattern values.\n");
  331. switch (test_pattern) {
  332. #if ENABLED(UBL_DEVEL_DEBUGGING)
  333. case -1:
  334. g29_eeprom_dump();
  335. break;
  336. #endif
  337. case 0:
  338. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) { // Create a bowl shape - similar to
  339. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++) { // a poorly calibrated Delta.
  340. const float p1 = 0.5f * (GRID_MAX_POINTS_X) - x,
  341. p2 = 0.5f * (GRID_MAX_POINTS_Y) - y;
  342. z_values[x][y] += 2.0f * HYPOT(p1, p2);
  343. }
  344. }
  345. break;
  346. case 1:
  347. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) { // Create a diagonal line several Mesh cells thick that is raised
  348. z_values[x][x] += 9.999f;
  349. z_values[x][x + (x < GRID_MAX_POINTS_Y - 1) ? 1 : -1] += 9.999f; // We want the altered line several mesh points thick
  350. }
  351. break;
  352. case 2:
  353. // Allow the user to specify the height because 10mm is a little extreme in some cases.
  354. for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in
  355. for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) // the center of the bed
  356. z_values[x][y] += parser.seen('C') ? g29_constant : 9.99f;
  357. break;
  358. }
  359. }
  360. #if HAS_BED_PROBE
  361. if (parser.seen('J')) {
  362. if (g29_grid_size) { // if not 0 it is a normal n x n grid being probed
  363. save_ubl_active_state_and_disable();
  364. tilt_mesh_based_on_probed_grid(false /* false says to do normal grid probing */ );
  365. restore_ubl_active_state_and_leave();
  366. }
  367. else { // grid_size == 0 : A 3-Point leveling has been requested
  368. save_ubl_active_state_and_disable();
  369. tilt_mesh_based_on_probed_grid(true /* true says to do 3-Point leveling */ );
  370. restore_ubl_active_state_and_leave();
  371. }
  372. do_blocking_move_to_xy(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)));
  373. report_current_position();
  374. }
  375. #endif // HAS_BED_PROBE
  376. if (parser.seen('P')) {
  377. if (WITHIN(g29_phase_value, 0, 1) && storage_slot == -1) {
  378. storage_slot = 0;
  379. SERIAL_ECHOLNPGM("Default storage slot 0 selected.");
  380. }
  381. switch (g29_phase_value) {
  382. case 0:
  383. //
  384. // Zero Mesh Data
  385. //
  386. reset();
  387. SERIAL_ECHOLNPGM("Mesh zeroed.");
  388. break;
  389. #if HAS_BED_PROBE
  390. case 1:
  391. //
  392. // Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
  393. //
  394. if (!parser.seen('C')) {
  395. invalidate();
  396. SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh.");
  397. }
  398. if (g29_verbose_level > 1) {
  399. SERIAL_ECHOPAIR("Probing Mesh Points Closest to (", g29_x_pos);
  400. SERIAL_CHAR(',');
  401. SERIAL_ECHO(g29_y_pos);
  402. SERIAL_ECHOLNPGM(").\n");
  403. }
  404. probe_entire_mesh(g29_x_pos + X_PROBE_OFFSET_FROM_EXTRUDER, g29_y_pos + Y_PROBE_OFFSET_FROM_EXTRUDER,
  405. parser.seen('T'), parser.seen('E'), parser.seen('U'));
  406. report_current_position();
  407. break;
  408. #endif // HAS_BED_PROBE
  409. case 2: {
  410. #if HAS_LCD_MENU
  411. //
  412. // Manually Probe Mesh in areas that can't be reached by the probe
  413. //
  414. SERIAL_ECHOLNPGM("Manually probing unreachable mesh locations.");
  415. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  416. if (parser.seen('C') && !g29_x_flag && !g29_y_flag) {
  417. /**
  418. * Use a good default location for the path.
  419. * The flipped > and < operators in these comparisons is intentional.
  420. * It should cause the probed points to follow a nice path on Cartesian printers.
  421. * It may make sense to have Delta printers default to the center of the bed.
  422. * Until that is decided, this can be forced with the X and Y parameters.
  423. */
  424. #if IS_KINEMATIC
  425. g29_x_pos = X_HOME_POS;
  426. g29_y_pos = Y_HOME_POS;
  427. #else // cartesian
  428. g29_x_pos = X_PROBE_OFFSET_FROM_EXTRUDER > 0 ? X_BED_SIZE : 0;
  429. g29_y_pos = Y_PROBE_OFFSET_FROM_EXTRUDER < 0 ? Y_BED_SIZE : 0;
  430. #endif
  431. }
  432. if (parser.seen('B')) {
  433. g29_card_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness((float) Z_CLEARANCE_BETWEEN_PROBES);
  434. if (ABS(g29_card_thickness) > 1.5f) {
  435. SERIAL_ECHOLNPGM("?Error in Business Card measurement.");
  436. return;
  437. }
  438. }
  439. if (!position_is_reachable(g29_x_pos, g29_y_pos)) {
  440. SERIAL_ECHOLNPGM("XY outside printable radius.");
  441. return;
  442. }
  443. const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES);
  444. manually_probe_remaining_mesh(g29_x_pos, g29_y_pos, height, g29_card_thickness, parser.seen('T'));
  445. SERIAL_ECHOLNPGM("G29 P2 finished.");
  446. report_current_position();
  447. #else
  448. SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present.");
  449. return;
  450. #endif
  451. } break;
  452. case 3: {
  453. /**
  454. * Populate invalid mesh areas. Proceed with caution.
  455. * Two choices are available:
  456. * - Specify a constant with the 'C' parameter.
  457. * - Allow 'G29 P3' to choose a 'reasonable' constant.
  458. */
  459. if (g29_c_flag) {
  460. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  461. set_all_mesh_points_to_value(g29_constant);
  462. }
  463. else {
  464. while (g29_repetition_cnt--) { // this only populates reachable mesh points near
  465. const mesh_index_pair location = find_closest_mesh_point_of_type(INVALID, g29_x_pos, g29_y_pos, USE_NOZZLE_AS_REFERENCE, NULL);
  466. if (location.x_index < 0) {
  467. // No more REACHABLE INVALID mesh points to populate, so we ASSUME
  468. // user meant to populate ALL INVALID mesh points to value
  469. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  470. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  471. if (isnan(z_values[x][y]))
  472. z_values[x][y] = g29_constant;
  473. break; // No more invalid Mesh Points to populate
  474. }
  475. z_values[location.x_index][location.y_index] = g29_constant;
  476. }
  477. }
  478. }
  479. else {
  480. const float cvf = parser.value_float();
  481. switch ((int)truncf(cvf * 10.0f) - 30) { // 3.1 -> 1
  482. #if ENABLED(UBL_G29_P31)
  483. case 1: {
  484. // P3.1 use least squares fit to fill missing mesh values
  485. // P3.10 zero weighting for distance, all grid points equal, best fit tilted plane
  486. // P3.11 10X weighting for nearest grid points versus farthest grid points
  487. // P3.12 100X distance weighting
  488. // P3.13 1000X distance weighting, approaches simple average of nearest points
  489. const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345
  490. weight_factor = weight_power ? POW(10.0f, weight_power) : 0;
  491. smart_fill_wlsf(weight_factor);
  492. }
  493. break;
  494. #endif
  495. case 0: // P3 or P3.0
  496. default: // and anything P3.x that's not P3.1
  497. smart_fill_mesh(); // Do a 'Smart' fill using nearby known values
  498. break;
  499. }
  500. }
  501. break;
  502. }
  503. case 4: // Fine Tune (i.e., Edit) the Mesh
  504. #if HAS_LCD_MENU
  505. fine_tune_mesh(g29_x_pos, g29_y_pos, parser.seen('T'));
  506. #else
  507. SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present.");
  508. return;
  509. #endif
  510. break;
  511. case 5: adjust_mesh_to_mean(g29_c_flag, g29_constant); break;
  512. case 6: shift_mesh_height(); break;
  513. }
  514. }
  515. #if ENABLED(UBL_DEVEL_DEBUGGING)
  516. //
  517. // Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  518. // good to have the extra information. Soon... we prune this to just a few items
  519. //
  520. if (parser.seen('W')) g29_what_command();
  521. //
  522. // When we are fully debugged, this may go away. But there are some valid
  523. // use cases for the users. So we can wait and see what to do with it.
  524. //
  525. if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
  526. g29_compare_current_mesh_to_stored_mesh();
  527. #endif // UBL_DEVEL_DEBUGGING
  528. //
  529. // Load a Mesh from the EEPROM
  530. //
  531. if (parser.seen('L')) { // Load Current Mesh Data
  532. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  533. int16_t a = settings.calc_num_meshes();
  534. if (!a) {
  535. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  536. return;
  537. }
  538. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  539. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  540. return;
  541. }
  542. settings.load_mesh(g29_storage_slot);
  543. storage_slot = g29_storage_slot;
  544. SERIAL_ECHOLNPGM("Done.");
  545. }
  546. //
  547. // Store a Mesh in the EEPROM
  548. //
  549. if (parser.seen('S')) { // Store (or Save) Current Mesh Data
  550. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  551. if (g29_storage_slot == -1) // Special case, the user wants to 'Export' the mesh to the
  552. return report_current_mesh(); // host program to be saved on the user's computer
  553. int16_t a = settings.calc_num_meshes();
  554. if (!a) {
  555. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  556. goto LEAVE;
  557. }
  558. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  559. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  560. goto LEAVE;
  561. }
  562. settings.store_mesh(g29_storage_slot);
  563. storage_slot = g29_storage_slot;
  564. SERIAL_ECHOLNPGM("Done.");
  565. }
  566. if (parser.seen('T'))
  567. display_map(g29_map_type);
  568. LEAVE:
  569. #if HAS_LCD_MENU
  570. ui.reset_alert_level();
  571. ui.quick_feedback();
  572. ui.reset_status();
  573. ui.release();
  574. #endif
  575. return;
  576. }
  577. void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const float value) {
  578. float sum = 0;
  579. int n = 0;
  580. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  581. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  582. if (!isnan(z_values[x][y])) {
  583. sum += z_values[x][y];
  584. n++;
  585. }
  586. const float mean = sum / n;
  587. //
  588. // Sum the squares of difference from mean
  589. //
  590. float sum_of_diff_squared = 0;
  591. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  592. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  593. if (!isnan(z_values[x][y]))
  594. sum_of_diff_squared += sq(z_values[x][y] - mean);
  595. SERIAL_ECHOLNPAIR("# of samples: ", n);
  596. SERIAL_ECHOLNPAIR_F("Mean Mesh Height: ", mean, 6);
  597. const float sigma = SQRT(sum_of_diff_squared / (n + 1));
  598. SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6);
  599. if (cflag)
  600. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  601. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  602. if (!isnan(z_values[x][y]))
  603. z_values[x][y] -= mean + value;
  604. }
  605. void unified_bed_leveling::shift_mesh_height() {
  606. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  607. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  608. if (!isnan(z_values[x][y]))
  609. z_values[x][y] += g29_constant;
  610. }
  611. #if HAS_BED_PROBE
  612. /**
  613. * Probe all invalidated locations of the mesh that can be reached by the probe.
  614. * This attempts to fill in locations closest to the nozzle's start location first.
  615. */
  616. void unified_bed_leveling::probe_entire_mesh(const float &rx, const float &ry, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) {
  617. mesh_index_pair location;
  618. #if HAS_LCD_MENU
  619. ui.capture();
  620. #endif
  621. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  622. DEPLOY_PROBE();
  623. uint16_t count = GRID_MAX_POINTS;
  624. do {
  625. if (do_ubl_mesh_map) display_map(g29_map_type);
  626. #if HAS_LCD_MENU
  627. if (ui.button_pressed()) {
  628. ui.quick_feedback(false); // Preserve button state for click-and-hold
  629. SERIAL_ECHOLNPGM("\nMesh only partially populated.\n");
  630. STOW_PROBE();
  631. ui.wait_for_release();
  632. ui.quick_feedback();
  633. ui.release();
  634. restore_ubl_active_state_and_leave();
  635. return;
  636. }
  637. #endif
  638. if (do_furthest)
  639. location = find_furthest_invalid_mesh_point();
  640. else
  641. location = find_closest_mesh_point_of_type(INVALID, rx, ry, USE_PROBE_AS_REFERENCE, NULL);
  642. if (location.x_index >= 0) { // mesh point found and is reachable by probe
  643. const float rawx = mesh_index_to_xpos(location.x_index),
  644. rawy = mesh_index_to_ypos(location.y_index);
  645. const float measured_z = probe_pt(rawx, rawy, stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level); // TODO: Needs error handling
  646. z_values[location.x_index][location.y_index] = measured_z;
  647. }
  648. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  649. } while (location.x_index >= 0 && --count);
  650. STOW_PROBE();
  651. #ifdef Z_AFTER_PROBING
  652. move_z_after_probing();
  653. #endif
  654. restore_ubl_active_state_and_leave();
  655. do_blocking_move_to_xy(
  656. constrain(rx - (X_PROBE_OFFSET_FROM_EXTRUDER), MESH_MIN_X, MESH_MAX_X),
  657. constrain(ry - (Y_PROBE_OFFSET_FROM_EXTRUDER), MESH_MIN_Y, MESH_MAX_Y)
  658. );
  659. }
  660. #endif // HAS_BED_PROBE
  661. #if HAS_LCD_MENU
  662. typedef void (*clickFunc_t)();
  663. bool click_and_hold(const clickFunc_t func=NULL) {
  664. if (ui.button_pressed()) {
  665. ui.quick_feedback(false); // Preserve button state for click-and-hold
  666. const millis_t nxt = millis() + 1500UL;
  667. while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag!
  668. idle(); // idle, of course
  669. if (ELAPSED(millis(), nxt)) { // After 1.5 seconds
  670. ui.quick_feedback();
  671. if (func) (*func)();
  672. ui.wait_for_release();
  673. return true;
  674. }
  675. }
  676. }
  677. serial_delay(15);
  678. return false;
  679. }
  680. void unified_bed_leveling::move_z_with_encoder(const float &multiplier) {
  681. ui.wait_for_release();
  682. while (!ui.button_pressed()) {
  683. idle();
  684. gcode.reset_stepper_timeout(); // Keep steppers powered
  685. if (encoder_diff) {
  686. do_blocking_move_to_z(current_position[Z_AXIS] + float(encoder_diff) * multiplier);
  687. encoder_diff = 0;
  688. }
  689. }
  690. }
  691. float unified_bed_leveling::measure_point_with_encoder() {
  692. KEEPALIVE_STATE(PAUSED_FOR_USER);
  693. move_z_with_encoder(0.01f);
  694. KEEPALIVE_STATE(IN_HANDLER);
  695. return current_position[Z_AXIS];
  696. }
  697. static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); }
  698. float unified_bed_leveling::measure_business_card_thickness(float in_height) {
  699. ui.capture();
  700. save_ubl_active_state_and_disable(); // Disable bed level correction for probing
  701. do_blocking_move_to(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)), in_height);
  702. //, MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f);
  703. planner.synchronize();
  704. SERIAL_ECHOPGM("Place shim under nozzle");
  705. LCD_MESSAGEPGM(MSG_UBL_BC_INSERT);
  706. ui.return_to_status();
  707. echo_and_take_a_measurement();
  708. const float z1 = measure_point_with_encoder();
  709. do_blocking_move_to_z(current_position[Z_AXIS] + SIZE_OF_LITTLE_RAISE);
  710. planner.synchronize();
  711. SERIAL_ECHOPGM("Remove shim");
  712. LCD_MESSAGEPGM(MSG_UBL_BC_REMOVE);
  713. echo_and_take_a_measurement();
  714. const float z2 = measure_point_with_encoder();
  715. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_BETWEEN_PROBES);
  716. const float thickness = ABS(z1 - z2);
  717. if (g29_verbose_level > 1) {
  718. SERIAL_ECHOPAIR_F("Business Card is ", thickness, 4);
  719. SERIAL_ECHOLNPGM("mm thick.");
  720. }
  721. ui.release();
  722. restore_ubl_active_state_and_leave();
  723. return thickness;
  724. }
  725. void abort_manual_probe_remaining_mesh() {
  726. SERIAL_ECHOLNPGM("\nMesh only partially populated.");
  727. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  728. ui.release();
  729. KEEPALIVE_STATE(IN_HANDLER);
  730. ui.quick_feedback();
  731. ubl.restore_ubl_active_state_and_leave();
  732. }
  733. void unified_bed_leveling::manually_probe_remaining_mesh(const float &rx, const float &ry, const float &z_clearance, const float &thick, const bool do_ubl_mesh_map) {
  734. ui.capture();
  735. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  736. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_clearance);
  737. ui.return_to_status();
  738. mesh_index_pair location;
  739. do {
  740. location = find_closest_mesh_point_of_type(INVALID, rx, ry, USE_NOZZLE_AS_REFERENCE, NULL);
  741. // It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
  742. if (location.x_index < 0 && location.y_index < 0) continue;
  743. const float xProbe = mesh_index_to_xpos(location.x_index),
  744. yProbe = mesh_index_to_ypos(location.y_index);
  745. if (!position_is_reachable(xProbe, yProbe)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points)
  746. LCD_MESSAGEPGM(MSG_UBL_MOVING_TO_NEXT);
  747. do_blocking_move_to(xProbe, yProbe, Z_CLEARANCE_BETWEEN_PROBES);
  748. do_blocking_move_to_z(z_clearance);
  749. KEEPALIVE_STATE(PAUSED_FOR_USER);
  750. ui.capture();
  751. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  752. serialprintPGM(parser.seen('B') ? PSTR(MSG_UBL_BC_INSERT) : PSTR(MSG_UBL_BC_INSERT2));
  753. const float z_step = 0.01f; // existing behavior: 0.01mm per click, occasionally step
  754. //const float z_step = planner.steps_to_mm[Z_AXIS]; // approx one step each click
  755. move_z_with_encoder(z_step);
  756. if (click_and_hold()) {
  757. SERIAL_ECHOLNPGM("\nMesh only partially populated.");
  758. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  759. ui.release();
  760. KEEPALIVE_STATE(IN_HANDLER);
  761. restore_ubl_active_state_and_leave();
  762. return;
  763. }
  764. z_values[location.x_index][location.y_index] = current_position[Z_AXIS] - thick;
  765. if (g29_verbose_level > 2)
  766. SERIAL_ECHOLNPAIR_F("Mesh Point Measured at: ", z_values[location.x_index][location.y_index], 6);
  767. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  768. } while (location.x_index >= 0 && location.y_index >= 0);
  769. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  770. restore_ubl_active_state_and_leave();
  771. KEEPALIVE_STATE(IN_HANDLER);
  772. do_blocking_move_to(rx, ry, Z_CLEARANCE_DEPLOY_PROBE);
  773. }
  774. inline void set_message_with_feedback(PGM_P const msg_P) {
  775. ui.set_status_P(msg_P);
  776. ui.quick_feedback();
  777. }
  778. void abort_fine_tune() {
  779. ui.return_to_status();
  780. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  781. set_message_with_feedback(PSTR(MSG_EDITING_STOPPED));
  782. }
  783. void unified_bed_leveling::fine_tune_mesh(const float &rx, const float &ry, const bool do_ubl_mesh_map) {
  784. if (!parser.seen('R')) // fine_tune_mesh() is special. If no repetition count flag is specified
  785. g29_repetition_cnt = 1; // do exactly one mesh location. Otherwise use what the parser decided.
  786. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  787. const float h_offset = parser.seenval('H') ? parser.value_linear_units() : 0;
  788. if (!WITHIN(h_offset, 0, 10)) {
  789. SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n");
  790. return;
  791. }
  792. #endif
  793. mesh_index_pair location;
  794. if (!position_is_reachable(rx, ry)) {
  795. SERIAL_ECHOLNPGM("(X,Y) outside printable radius.");
  796. return;
  797. }
  798. save_ubl_active_state_and_disable();
  799. LCD_MESSAGEPGM(MSG_UBL_FINE_TUNE_MESH);
  800. ui.capture(); // Take over control of the LCD encoder
  801. do_blocking_move_to(rx, ry, Z_CLEARANCE_BETWEEN_PROBES); // Move to the given XY with probe clearance
  802. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  803. do_blocking_move_to_z(h_offset); // Move Z to the given 'H' offset
  804. #endif
  805. uint16_t not_done[16];
  806. memset(not_done, 0xFF, sizeof(not_done));
  807. do {
  808. location = find_closest_mesh_point_of_type(SET_IN_BITMAP, rx, ry, USE_NOZZLE_AS_REFERENCE, not_done);
  809. if (location.x_index < 0) break; // Stop when there are no more reachable points
  810. bitmap_clear(not_done, location.x_index, location.y_index); // Mark this location as 'adjusted' so a new
  811. // location is used on the next loop
  812. const float rawx = mesh_index_to_xpos(location.x_index),
  813. rawy = mesh_index_to_ypos(location.y_index);
  814. if (!position_is_reachable(rawx, rawy)) break; // SHOULD NOT OCCUR because find_closest_mesh_point_of_type will only return reachable
  815. do_blocking_move_to(rawx, rawy, Z_CLEARANCE_BETWEEN_PROBES); // Move the nozzle to the edit point with probe clearance
  816. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  817. do_blocking_move_to_z(h_offset); // Move Z to the given 'H' offset before editing
  818. #endif
  819. KEEPALIVE_STATE(PAUSED_FOR_USER);
  820. if (do_ubl_mesh_map) display_map(g29_map_type); // Display the current point
  821. ui.refresh();
  822. float new_z = z_values[location.x_index][location.y_index];
  823. if (isnan(new_z)) new_z = 0; // Invalid points begin at 0
  824. new_z = FLOOR(new_z * 1000) * 0.001f; // Chop off digits after the 1000ths place
  825. lcd_mesh_edit_setup(new_z);
  826. do {
  827. new_z = lcd_mesh_edit();
  828. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  829. do_blocking_move_to_z(h_offset + new_z); // Move the nozzle as the point is edited
  830. #endif
  831. idle();
  832. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  833. } while (!ui.button_pressed());
  834. if (!lcd_map_control) ui.return_to_status(); // Just editing a single point? Return to status
  835. if (click_and_hold(abort_fine_tune)) goto FINE_TUNE_EXIT; // If the click is held down, abort editing
  836. z_values[location.x_index][location.y_index] = new_z; // Save the updated Z value
  837. serial_delay(20); // No switch noise
  838. ui.refresh();
  839. } while (location.x_index >= 0 && --g29_repetition_cnt > 0);
  840. FINE_TUNE_EXIT:
  841. ui.release();
  842. KEEPALIVE_STATE(IN_HANDLER);
  843. if (do_ubl_mesh_map) display_map(g29_map_type);
  844. restore_ubl_active_state_and_leave();
  845. do_blocking_move_to(rx, ry, Z_CLEARANCE_BETWEEN_PROBES);
  846. LCD_MESSAGEPGM(MSG_UBL_DONE_EDITING_MESH);
  847. SERIAL_ECHOLNPGM("Done Editing Mesh");
  848. if (lcd_map_control)
  849. ui.goto_screen(_lcd_ubl_output_map_lcd);
  850. else
  851. ui.return_to_status();
  852. }
  853. #endif // HAS_LCD_MENU
  854. bool unified_bed_leveling::g29_parameter_parsing() {
  855. bool err_flag = false;
  856. #if HAS_LCD_MENU
  857. set_message_with_feedback(PSTR(MSG_UBL_DOING_G29));
  858. #endif
  859. g29_constant = 0;
  860. g29_repetition_cnt = 0;
  861. g29_x_flag = parser.seenval('X');
  862. g29_x_pos = g29_x_flag ? parser.value_float() : current_position[X_AXIS];
  863. g29_y_flag = parser.seenval('Y');
  864. g29_y_pos = g29_y_flag ? parser.value_float() : current_position[Y_AXIS];
  865. if (parser.seen('R')) {
  866. g29_repetition_cnt = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS;
  867. NOMORE(g29_repetition_cnt, GRID_MAX_POINTS);
  868. if (g29_repetition_cnt < 1) {
  869. SERIAL_ECHOLNPGM("?(R)epetition count invalid (1+).\n");
  870. return UBL_ERR;
  871. }
  872. }
  873. g29_verbose_level = parser.seen('V') ? parser.value_int() : 0;
  874. if (!WITHIN(g29_verbose_level, 0, 4)) {
  875. SERIAL_ECHOLNPGM("?(V)erbose level is implausible (0-4).\n");
  876. err_flag = true;
  877. }
  878. if (parser.seen('P')) {
  879. const int pv = parser.value_int();
  880. #if !HAS_BED_PROBE
  881. if (pv == 1) {
  882. SERIAL_ECHOLNPGM("G29 P1 requires a probe.\n");
  883. err_flag = true;
  884. }
  885. else
  886. #endif
  887. {
  888. g29_phase_value = pv;
  889. if (!WITHIN(g29_phase_value, 0, 6)) {
  890. SERIAL_ECHOLNPGM("?(P)hase value invalid (0-6).\n");
  891. err_flag = true;
  892. }
  893. }
  894. }
  895. if (parser.seen('J')) {
  896. #if HAS_BED_PROBE
  897. g29_grid_size = parser.has_value() ? parser.value_int() : 0;
  898. if (g29_grid_size && !WITHIN(g29_grid_size, 2, 9)) {
  899. SERIAL_ECHOLNPGM("?Invalid grid size (J) specified (2-9).\n");
  900. err_flag = true;
  901. }
  902. #else
  903. SERIAL_ECHOLNPGM("G29 J action requires a probe.\n");
  904. err_flag = true;
  905. #endif
  906. }
  907. if (g29_x_flag != g29_y_flag) {
  908. SERIAL_ECHOLNPGM("Both X & Y locations must be specified.\n");
  909. err_flag = true;
  910. }
  911. // If X or Y are not valid, use center of the bed values
  912. if (!WITHIN(g29_x_pos, X_MIN_BED, X_MAX_BED)) g29_x_pos = X_CENTER;
  913. if (!WITHIN(g29_y_pos, Y_MIN_BED, Y_MAX_BED)) g29_y_pos = Y_CENTER;
  914. if (err_flag) return UBL_ERR;
  915. /**
  916. * Activate or deactivate UBL
  917. * Note: UBL's G29 restores the state set here when done.
  918. * Leveling is being enabled here with old data, possibly
  919. * none. Error handling should disable for safety...
  920. */
  921. if (parser.seen('A')) {
  922. if (parser.seen('D')) {
  923. SERIAL_ECHOLNPGM("?Can't activate and deactivate at the same time.\n");
  924. return UBL_ERR;
  925. }
  926. set_bed_leveling_enabled(true);
  927. report_state();
  928. }
  929. else if (parser.seen('D')) {
  930. set_bed_leveling_enabled(false);
  931. report_state();
  932. }
  933. // Set global 'C' flag and its value
  934. if ((g29_c_flag = parser.seen('C')))
  935. g29_constant = parser.value_float();
  936. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  937. if (parser.seenval('F')) {
  938. const float fh = parser.value_float();
  939. if (!WITHIN(fh, 0, 100)) {
  940. SERIAL_ECHOLNPGM("?(F)ade height for Bed Level Correction not plausible.\n");
  941. return UBL_ERR;
  942. }
  943. set_z_fade_height(fh);
  944. }
  945. #endif
  946. g29_map_type = parser.intval('T');
  947. if (!WITHIN(g29_map_type, 0, 2)) {
  948. SERIAL_ECHOLNPGM("Invalid map type.\n");
  949. return UBL_ERR;
  950. }
  951. return UBL_OK;
  952. }
  953. static uint8_t ubl_state_at_invocation = 0;
  954. #if ENABLED(UBL_DEVEL_DEBUGGING)
  955. static uint8_t ubl_state_recursion_chk = 0;
  956. #endif
  957. void unified_bed_leveling::save_ubl_active_state_and_disable() {
  958. #if ENABLED(UBL_DEVEL_DEBUGGING)
  959. ubl_state_recursion_chk++;
  960. if (ubl_state_recursion_chk != 1) {
  961. SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row.");
  962. #if HAS_LCD_MENU
  963. set_message_with_feedback(PSTR(MSG_UBL_SAVE_ERROR));
  964. #endif
  965. return;
  966. }
  967. #endif
  968. ubl_state_at_invocation = planner.leveling_active;
  969. set_bed_leveling_enabled(false);
  970. }
  971. void unified_bed_leveling::restore_ubl_active_state_and_leave() {
  972. #if ENABLED(UBL_DEVEL_DEBUGGING)
  973. if (--ubl_state_recursion_chk) {
  974. SERIAL_ECHOLNPGM("restore_ubl_active_state_and_leave() called too many times.");
  975. #if HAS_LCD_MENU
  976. set_message_with_feedback(PSTR(MSG_UBL_RESTORE_ERROR));
  977. #endif
  978. return;
  979. }
  980. #endif
  981. set_bed_leveling_enabled(ubl_state_at_invocation);
  982. }
  983. mesh_index_pair unified_bed_leveling::find_furthest_invalid_mesh_point() {
  984. bool found_a_NAN = false, found_a_real = false;
  985. mesh_index_pair out_mesh;
  986. out_mesh.x_index = out_mesh.y_index = -1;
  987. out_mesh.distance = -99999.99f;
  988. for (int8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  989. for (int8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
  990. if (isnan(z_values[i][j])) { // Check to see if this location holds an invalid mesh point
  991. const float mx = mesh_index_to_xpos(i),
  992. my = mesh_index_to_ypos(j);
  993. if (!position_is_reachable_by_probe(mx, my)) // make sure the probe can get to the mesh point
  994. continue;
  995. found_a_NAN = true;
  996. int8_t closest_x = -1, closest_y = -1;
  997. float d1, d2 = 99999.9f;
  998. for (int8_t k = 0; k < GRID_MAX_POINTS_X; k++) {
  999. for (int8_t l = 0; l < GRID_MAX_POINTS_Y; l++) {
  1000. if (!isnan(z_values[k][l])) {
  1001. found_a_real = true;
  1002. // Add in a random weighting factor that scrambles the probing of the
  1003. // last half of the mesh (when every unprobed mesh point is one index
  1004. // from a probed location).
  1005. d1 = HYPOT(i - k, j - l) + (1.0f / ((millis() % 47) + 13));
  1006. if (d1 < d2) { // found a closer distance from invalid mesh point at (i,j) to defined mesh point at (k,l)
  1007. d2 = d1; // found a closer location with
  1008. closest_x = i; // an assigned mesh point value
  1009. closest_y = j;
  1010. }
  1011. }
  1012. }
  1013. }
  1014. //
  1015. // At this point d2 should have the closest defined mesh point to invalid mesh point (i,j)
  1016. //
  1017. if (found_a_real && (closest_x >= 0) && (d2 > out_mesh.distance)) {
  1018. out_mesh.distance = d2; // found an invalid location with a greater distance
  1019. out_mesh.x_index = closest_x; // to a defined mesh point
  1020. out_mesh.y_index = closest_y;
  1021. }
  1022. }
  1023. } // for j
  1024. } // for i
  1025. if (!found_a_real && found_a_NAN) { // if the mesh is totally unpopulated, start the probing
  1026. out_mesh.x_index = GRID_MAX_POINTS_X / 2;
  1027. out_mesh.y_index = GRID_MAX_POINTS_Y / 2;
  1028. out_mesh.distance = 1;
  1029. }
  1030. return out_mesh;
  1031. }
  1032. mesh_index_pair unified_bed_leveling::find_closest_mesh_point_of_type(const MeshPointType type, const float &rx, const float &ry, const bool probe_as_reference, uint16_t bits[16]) {
  1033. mesh_index_pair out_mesh;
  1034. out_mesh.x_index = out_mesh.y_index = -1;
  1035. out_mesh.distance = -99999.9f;
  1036. // Get our reference position. Either the nozzle or probe location.
  1037. const float px = rx + (probe_as_reference == USE_PROBE_AS_REFERENCE ? X_PROBE_OFFSET_FROM_EXTRUDER : 0),
  1038. py = ry + (probe_as_reference == USE_PROBE_AS_REFERENCE ? Y_PROBE_OFFSET_FROM_EXTRUDER : 0);
  1039. float best_so_far = 99999.99f;
  1040. for (int8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1041. for (int8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
  1042. if ( (type == INVALID && isnan(z_values[i][j])) // Check to see if this location holds the right thing
  1043. || (type == REAL && !isnan(z_values[i][j]))
  1044. || (type == SET_IN_BITMAP && is_bitmap_set(bits, i, j))
  1045. ) {
  1046. // We only get here if we found a Mesh Point of the specified type
  1047. const float mx = mesh_index_to_xpos(i),
  1048. my = mesh_index_to_ypos(j);
  1049. // If using the probe as the reference there are some unreachable locations.
  1050. // Also for round beds, there are grid points outside the bed the nozzle can't reach.
  1051. // Prune them from the list and ignore them till the next Phase (manual nozzle probing).
  1052. if (probe_as_reference ? !position_is_reachable_by_probe(mx, my) : !position_is_reachable(mx, my))
  1053. continue;
  1054. // Reachable. Check if it's the best_so_far location to the nozzle.
  1055. float distance = HYPOT(px - mx, py - my);
  1056. // factor in the distance from the current location for the normal case
  1057. // so the nozzle isn't running all over the bed.
  1058. distance += HYPOT(current_position[X_AXIS] - mx, current_position[Y_AXIS] - my) * 0.1f;
  1059. if (distance < best_so_far) {
  1060. best_so_far = distance; // We found a closer location with
  1061. out_mesh.x_index = i; // the specified type of mesh value.
  1062. out_mesh.y_index = j;
  1063. out_mesh.distance = best_so_far;
  1064. }
  1065. }
  1066. } // for j
  1067. } // for i
  1068. return out_mesh;
  1069. }
  1070. /**
  1071. * 'Smart Fill': Scan from the outward edges of the mesh towards the center.
  1072. * If an invalid location is found, use the next two points (if valid) to
  1073. * calculate a 'reasonable' value for the unprobed mesh point.
  1074. */
  1075. bool unified_bed_leveling::smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  1076. const int8_t x1 = x + xdir, x2 = x1 + xdir,
  1077. y1 = y + ydir, y2 = y1 + ydir;
  1078. // A NAN next to a pair of real values?
  1079. if (isnan(z_values[x][y]) && !isnan(z_values[x1][y1]) && !isnan(z_values[x2][y2])) {
  1080. if (z_values[x1][y1] < z_values[x2][y2]) // Angled downward?
  1081. z_values[x][y] = z_values[x1][y1]; // Use nearest (maybe a little too high.)
  1082. else
  1083. z_values[x][y] = 2.0f * z_values[x1][y1] - z_values[x2][y2]; // Angled upward...
  1084. return true;
  1085. }
  1086. return false;
  1087. }
  1088. typedef struct { uint8_t sx, ex, sy, ey; bool yfirst; } smart_fill_info;
  1089. void unified_bed_leveling::smart_fill_mesh() {
  1090. static const smart_fill_info
  1091. info0 PROGMEM = { 0, GRID_MAX_POINTS_X, 0, GRID_MAX_POINTS_Y - 2, false }, // Bottom of the mesh looking up
  1092. info1 PROGMEM = { 0, GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y - 1, 0, false }, // Top of the mesh looking down
  1093. info2 PROGMEM = { 0, GRID_MAX_POINTS_X - 2, 0, GRID_MAX_POINTS_Y, true }, // Left side of the mesh looking right
  1094. info3 PROGMEM = { GRID_MAX_POINTS_X - 1, 0, 0, GRID_MAX_POINTS_Y, true }; // Right side of the mesh looking left
  1095. static const smart_fill_info * const info[] PROGMEM = { &info0, &info1, &info2, &info3 };
  1096. for (uint8_t i = 0; i < COUNT(info); ++i) {
  1097. const smart_fill_info *f = (smart_fill_info*)pgm_read_ptr(&info[i]);
  1098. const int8_t sx = pgm_read_byte(&f->sx), sy = pgm_read_byte(&f->sy),
  1099. ex = pgm_read_byte(&f->ex), ey = pgm_read_byte(&f->ey);
  1100. if (pgm_read_byte(&f->yfirst)) {
  1101. const int8_t dir = ex > sx ? 1 : -1;
  1102. for (uint8_t y = sy; y != ey; ++y)
  1103. for (uint8_t x = sx; x != ex; x += dir)
  1104. if (smart_fill_one(x, y, dir, 0)) break;
  1105. }
  1106. else {
  1107. const int8_t dir = ey > sy ? 1 : -1;
  1108. for (uint8_t x = sx; x != ex; ++x)
  1109. for (uint8_t y = sy; y != ey; y += dir)
  1110. if (smart_fill_one(x, y, 0, dir)) break;
  1111. }
  1112. }
  1113. }
  1114. #if HAS_BED_PROBE
  1115. #include "../../../libs/vector_3.h"
  1116. void unified_bed_leveling::tilt_mesh_based_on_probed_grid(const bool do_3_pt_leveling) {
  1117. constexpr int16_t x_min = MAX(MIN_PROBE_X, MESH_MIN_X),
  1118. x_max = MIN(MAX_PROBE_X, MESH_MAX_X),
  1119. y_min = MAX(MIN_PROBE_Y, MESH_MIN_Y),
  1120. y_max = MIN(MAX_PROBE_Y, MESH_MAX_Y);
  1121. bool abort_flag = false;
  1122. float measured_z;
  1123. const float dx = float(x_max - x_min) / (g29_grid_size - 1),
  1124. dy = float(y_max - y_min) / (g29_grid_size - 1);
  1125. struct linear_fit_data lsf_results;
  1126. //float z1, z2, z3; // Needed for algorithm validation down below.
  1127. incremental_LSF_reset(&lsf_results);
  1128. if (do_3_pt_leveling) {
  1129. measured_z = probe_pt(PROBE_PT_1_X, PROBE_PT_1_Y, PROBE_PT_RAISE, g29_verbose_level);
  1130. if (isnan(measured_z))
  1131. abort_flag = true;
  1132. else {
  1133. measured_z -= get_z_correction(PROBE_PT_1_X, PROBE_PT_1_Y);
  1134. //z1 = measured_z;
  1135. if (g29_verbose_level > 3) {
  1136. serial_spaces(16);
  1137. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1138. }
  1139. incremental_LSF(&lsf_results, PROBE_PT_1_X, PROBE_PT_1_Y, measured_z);
  1140. }
  1141. if (!abort_flag) {
  1142. measured_z = probe_pt(PROBE_PT_2_X, PROBE_PT_2_Y, PROBE_PT_RAISE, g29_verbose_level);
  1143. //z2 = measured_z;
  1144. if (isnan(measured_z))
  1145. abort_flag = true;
  1146. else {
  1147. measured_z -= get_z_correction(PROBE_PT_2_X, PROBE_PT_2_Y);
  1148. if (g29_verbose_level > 3) {
  1149. serial_spaces(16);
  1150. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1151. }
  1152. incremental_LSF(&lsf_results, PROBE_PT_2_X, PROBE_PT_2_Y, measured_z);
  1153. }
  1154. }
  1155. if (!abort_flag) {
  1156. measured_z = probe_pt(PROBE_PT_3_X, PROBE_PT_3_Y, PROBE_PT_STOW, g29_verbose_level);
  1157. //z3 = measured_z;
  1158. if (isnan(measured_z))
  1159. abort_flag = true;
  1160. else {
  1161. measured_z -= get_z_correction(PROBE_PT_3_X, PROBE_PT_3_Y);
  1162. if (g29_verbose_level > 3) {
  1163. serial_spaces(16);
  1164. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1165. }
  1166. incremental_LSF(&lsf_results, PROBE_PT_3_X, PROBE_PT_3_Y, measured_z);
  1167. }
  1168. }
  1169. STOW_PROBE();
  1170. #ifdef Z_AFTER_PROBING
  1171. move_z_after_probing();
  1172. #endif
  1173. if (abort_flag) {
  1174. SERIAL_ECHOLNPGM("?Error probing point. Aborting operation.");
  1175. return;
  1176. }
  1177. }
  1178. else { // !do_3_pt_leveling
  1179. bool zig_zag = false;
  1180. for (uint8_t ix = 0; ix < g29_grid_size; ix++) {
  1181. const float rx = float(x_min) + ix * dx;
  1182. for (int8_t iy = 0; iy < g29_grid_size; iy++) {
  1183. const float ry = float(y_min) + dy * (zig_zag ? g29_grid_size - 1 - iy : iy);
  1184. if (!abort_flag) {
  1185. measured_z = probe_pt(rx, ry, parser.seen('E') ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level); // TODO: Needs error handling
  1186. abort_flag = isnan(measured_z);
  1187. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1188. if (DEBUGGING(LEVELING)) {
  1189. SERIAL_CHAR('(');
  1190. SERIAL_ECHO_F(rx, 7);
  1191. SERIAL_CHAR(',');
  1192. SERIAL_ECHO_F(ry, 7);
  1193. SERIAL_ECHOPGM(") logical: ");
  1194. SERIAL_CHAR('(');
  1195. SERIAL_ECHO_F(LOGICAL_X_POSITION(rx), 7);
  1196. SERIAL_CHAR(',');
  1197. SERIAL_ECHO_F(LOGICAL_Y_POSITION(ry), 7);
  1198. SERIAL_ECHOPAIR_F(") measured: ", measured_z, 7);
  1199. SERIAL_ECHOPAIR_F(" correction: ", get_z_correction(rx, ry), 7);
  1200. }
  1201. #endif
  1202. measured_z -= get_z_correction(rx, ry) /* + zprobe_zoffset */ ;
  1203. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1204. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR_F(" final >>>---> ", measured_z, 7);
  1205. #endif
  1206. if (g29_verbose_level > 3) {
  1207. serial_spaces(16);
  1208. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1209. }
  1210. incremental_LSF(&lsf_results, rx, ry, measured_z);
  1211. }
  1212. }
  1213. zig_zag ^= true;
  1214. }
  1215. }
  1216. STOW_PROBE();
  1217. #ifdef Z_AFTER_PROBING
  1218. move_z_after_probing();
  1219. #endif
  1220. if (abort_flag || finish_incremental_LSF(&lsf_results)) {
  1221. SERIAL_ECHOPGM("Could not complete LSF!");
  1222. return;
  1223. }
  1224. vector_3 normal = vector_3(lsf_results.A, lsf_results.B, 1).get_normal();
  1225. if (g29_verbose_level > 2) {
  1226. SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1227. SERIAL_CHAR(',');
  1228. SERIAL_ECHO_F(normal.y, 7);
  1229. SERIAL_CHAR(',');
  1230. SERIAL_ECHO_F(normal.z, 7);
  1231. SERIAL_ECHOLNPGM("]");
  1232. }
  1233. matrix_3x3 rotation = matrix_3x3::create_look_at(vector_3(lsf_results.A, lsf_results.B, 1));
  1234. for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1235. for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
  1236. float x_tmp = mesh_index_to_xpos(i),
  1237. y_tmp = mesh_index_to_ypos(j),
  1238. z_tmp = z_values[i][j];
  1239. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1240. if (DEBUGGING(LEVELING)) {
  1241. SERIAL_ECHOPAIR_F("before rotation = [", x_tmp, 7);
  1242. SERIAL_CHAR(',');
  1243. SERIAL_ECHO_F(y_tmp, 7);
  1244. SERIAL_CHAR(',');
  1245. SERIAL_ECHO_F(z_tmp, 7);
  1246. SERIAL_ECHOPGM("] ---> ");
  1247. serial_delay(20);
  1248. }
  1249. #endif
  1250. apply_rotation_xyz(rotation, x_tmp, y_tmp, z_tmp);
  1251. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1252. if (DEBUGGING(LEVELING)) {
  1253. SERIAL_ECHOPAIR_F("after rotation = [", x_tmp, 7);
  1254. SERIAL_CHAR(',');
  1255. SERIAL_ECHO_F(y_tmp, 7);
  1256. SERIAL_CHAR(',');
  1257. SERIAL_ECHO_F(z_tmp, 7);
  1258. SERIAL_ECHOLNPGM("]");
  1259. serial_delay(55);
  1260. }
  1261. #endif
  1262. z_values[i][j] = z_tmp - lsf_results.D;
  1263. }
  1264. }
  1265. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1266. if (DEBUGGING(LEVELING)) {
  1267. rotation.debug(PSTR("rotation matrix:\n"));
  1268. SERIAL_ECHOPAIR_F("LSF Results A=", lsf_results.A, 7);
  1269. SERIAL_ECHOPAIR_F(" B=", lsf_results.B, 7);
  1270. SERIAL_ECHOLNPAIR_F(" D=", lsf_results.D, 7);
  1271. serial_delay(55);
  1272. SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1273. SERIAL_CHAR(',');
  1274. SERIAL_ECHO_F(normal.y, 7);
  1275. SERIAL_CHAR(',');
  1276. SERIAL_ECHO_F(normal.z, 7);
  1277. SERIAL_ECHOLNPGM("]");
  1278. SERIAL_EOL();
  1279. /**
  1280. * The following code can be used to check the validity of the mesh tilting algorithm.
  1281. * When a 3-Point Mesh Tilt is done, the same algorithm is used as the grid based tilting.
  1282. * The only difference is just 3 points are used in the calculations. That fact guarantees
  1283. * each probed point should have an exact match when a get_z_correction() for that location
  1284. * is calculated. The Z error between the probed point locations and the get_z_correction()
  1285. * numbers for those locations should be 0.
  1286. */
  1287. #if 0
  1288. float t, t1, d;
  1289. t = normal.x * (PROBE_PT_1_X) + normal.y * (PROBE_PT_1_Y);
  1290. d = t + normal.z * z1;
  1291. SERIAL_ECHOPAIR_F("D from 1st point: ", d, 6);
  1292. SERIAL_ECHOLNPAIR_F(" Z error: ", normal.z*z1-get_z_correction(PROBE_PT_1_X, PROBE_PT_1_Y), 6);
  1293. t = normal.x * (PROBE_PT_2_X) + normal.y * (PROBE_PT_2_Y);
  1294. d = t + normal.z * z2;
  1295. SERIAL_EOL();
  1296. SERIAL_ECHOPAIR_F("D from 2nd point: ", d, 6);
  1297. SERIAL_ECHOLNPAIR_F(" Z error: ", normal.z*z2-get_z_correction(PROBE_PT_2_X, PROBE_PT_2_Y), 6);
  1298. t = normal.x * (PROBE_PT_3_X) + normal.y * (PROBE_PT_3_Y);
  1299. d = t + normal.z * z3;
  1300. SERIAL_ECHOPAIR_F("D from 3rd point: ", d, 6);
  1301. SERIAL_ECHOLNPAIR_F(" Z error: ", normal.z*z3-get_z_correction(PROBE_PT_3_X, PROBE_PT_3_Y), 6);
  1302. t = normal.x * (Z_SAFE_HOMING_X_POINT) + normal.y * (Z_SAFE_HOMING_Y_POINT);
  1303. d = t + normal.z * 0;
  1304. SERIAL_ECHOLNPAIR_F("D from home location with Z=0 : ", d, 6);
  1305. t = normal.x * (Z_SAFE_HOMING_X_POINT) + normal.y * (Z_SAFE_HOMING_Y_POINT);
  1306. d = t + get_z_correction(Z_SAFE_HOMING_X_POINT, Z_SAFE_HOMING_Y_POINT); // normal.z * 0;
  1307. SERIAL_ECHOPAIR_F("D from home location using mesh value for Z: ", d, 6);
  1308. SERIAL_ECHOPAIR(" Z error: (", Z_SAFE_HOMING_X_POINT);
  1309. SERIAL_ECHOPAIR(",", Z_SAFE_HOMING_Y_POINT);
  1310. SERIAL_ECHOLNPAIR_F(") = ", get_z_correction(Z_SAFE_HOMING_X_POINT, Z_SAFE_HOMING_Y_POINT), 6);
  1311. #endif
  1312. } // DEBUGGING(LEVELING)
  1313. #endif
  1314. }
  1315. #endif // HAS_BED_PROBE
  1316. #if ENABLED(UBL_G29_P31)
  1317. void unified_bed_leveling::smart_fill_wlsf(const float &weight_factor) {
  1318. // For each undefined mesh point, compute a distance-weighted least squares fit
  1319. // from all the originally populated mesh points, weighted toward the point
  1320. // being extrapolated so that nearby points will have greater influence on
  1321. // the point being extrapolated. Then extrapolate the mesh point from WLSF.
  1322. static_assert(GRID_MAX_POINTS_Y <= 16, "GRID_MAX_POINTS_Y too big");
  1323. uint16_t bitmap[GRID_MAX_POINTS_X] = { 0 };
  1324. struct linear_fit_data lsf_results;
  1325. SERIAL_ECHOPGM("Extrapolating mesh...");
  1326. const float weight_scaled = weight_factor * MAX(MESH_X_DIST, MESH_Y_DIST);
  1327. for (uint8_t jx = 0; jx < GRID_MAX_POINTS_X; jx++)
  1328. for (uint8_t jy = 0; jy < GRID_MAX_POINTS_Y; jy++)
  1329. if (!isnan(z_values[jx][jy]))
  1330. SBI(bitmap[jx], jy);
  1331. for (uint8_t ix = 0; ix < GRID_MAX_POINTS_X; ix++) {
  1332. const float px = mesh_index_to_xpos(ix);
  1333. for (uint8_t iy = 0; iy < GRID_MAX_POINTS_Y; iy++) {
  1334. const float py = mesh_index_to_ypos(iy);
  1335. if (isnan(z_values[ix][iy])) {
  1336. // undefined mesh point at (px,py), compute weighted LSF from original valid mesh points.
  1337. incremental_LSF_reset(&lsf_results);
  1338. for (uint8_t jx = 0; jx < GRID_MAX_POINTS_X; jx++) {
  1339. const float rx = mesh_index_to_xpos(jx);
  1340. for (uint8_t jy = 0; jy < GRID_MAX_POINTS_Y; jy++) {
  1341. if (TEST(bitmap[jx], jy)) {
  1342. const float ry = mesh_index_to_ypos(jy),
  1343. rz = z_values[jx][jy],
  1344. w = 1 + weight_scaled / HYPOT((rx - px), (ry - py));
  1345. incremental_WLSF(&lsf_results, rx, ry, rz, w);
  1346. }
  1347. }
  1348. }
  1349. if (finish_incremental_LSF(&lsf_results)) {
  1350. SERIAL_ECHOLNPGM("Insufficient data");
  1351. return;
  1352. }
  1353. const float ez = -lsf_results.D - lsf_results.A * px - lsf_results.B * py;
  1354. z_values[ix][iy] = ez;
  1355. idle(); // housekeeping
  1356. }
  1357. }
  1358. }
  1359. SERIAL_ECHOLNPGM("done");
  1360. }
  1361. #endif // UBL_G29_P31
  1362. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1363. /**
  1364. * Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  1365. * good to have the extra information. Soon... we prune this to just a few items
  1366. */
  1367. void unified_bed_leveling::g29_what_command() {
  1368. report_state();
  1369. if (storage_slot == -1)
  1370. SERIAL_ECHOPGM("No Mesh Loaded.");
  1371. else
  1372. SERIAL_ECHOPAIR("Mesh ", storage_slot, " Loaded.");
  1373. SERIAL_EOL();
  1374. serial_delay(50);
  1375. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1376. SERIAL_ECHOLNPAIR_F("planner.z_fade_height : ", planner.z_fade_height, 4);
  1377. #endif
  1378. adjust_mesh_to_mean(g29_c_flag, g29_constant);
  1379. #if HAS_BED_PROBE
  1380. SERIAL_ECHOLNPAIR_F("zprobe_zoffset: ", zprobe_zoffset, 7);
  1381. #endif
  1382. SERIAL_ECHOLNPAIR("MESH_MIN_X " STRINGIFY(MESH_MIN_X) "=", MESH_MIN_X); serial_delay(50);
  1383. SERIAL_ECHOLNPAIR("MESH_MIN_Y " STRINGIFY(MESH_MIN_Y) "=", MESH_MIN_Y); serial_delay(50);
  1384. SERIAL_ECHOLNPAIR("MESH_MAX_X " STRINGIFY(MESH_MAX_X) "=", MESH_MAX_X); serial_delay(50);
  1385. SERIAL_ECHOLNPAIR("MESH_MAX_Y " STRINGIFY(MESH_MAX_Y) "=", MESH_MAX_Y); serial_delay(50);
  1386. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_X ", GRID_MAX_POINTS_X); serial_delay(50);
  1387. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y); serial_delay(50);
  1388. SERIAL_ECHOLNPAIR("MESH_X_DIST ", MESH_X_DIST);
  1389. SERIAL_ECHOLNPAIR("MESH_Y_DIST ", MESH_Y_DIST); serial_delay(50);
  1390. SERIAL_ECHOPGM("X-Axis Mesh Points at: ");
  1391. for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1392. SERIAL_ECHO_F(LOGICAL_X_POSITION(mesh_index_to_xpos(i)), 3);
  1393. SERIAL_ECHOPGM(" ");
  1394. serial_delay(25);
  1395. }
  1396. SERIAL_EOL();
  1397. SERIAL_ECHOPGM("Y-Axis Mesh Points at: ");
  1398. for (uint8_t i = 0; i < GRID_MAX_POINTS_Y; i++) {
  1399. SERIAL_ECHO_F(LOGICAL_Y_POSITION(mesh_index_to_ypos(i)), 3);
  1400. SERIAL_ECHOPGM(" ");
  1401. serial_delay(25);
  1402. }
  1403. SERIAL_EOL();
  1404. #if HAS_KILL
  1405. SERIAL_ECHOLNPAIR("Kill pin on :", int(KILL_PIN), " state:", READ(KILL_PIN));
  1406. #endif
  1407. SERIAL_EOL();
  1408. serial_delay(50);
  1409. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1410. SERIAL_ECHOLNPAIR("ubl_state_at_invocation :", ubl_state_at_invocation, "\nubl_state_recursion_chk :", ubl_state_recursion_chk);
  1411. serial_delay(50);
  1412. SERIAL_ECHOLNPAIR("Meshes go from ", hex_address((void*)settings.meshes_start_index()), " to ", hex_address((void*)settings.meshes_end_index()));
  1413. serial_delay(50);
  1414. SERIAL_ECHOLNPAIR("sizeof(ubl) : ", (int)sizeof(ubl)); SERIAL_EOL();
  1415. SERIAL_ECHOLNPAIR("z_value[][] size: ", (int)sizeof(z_values)); SERIAL_EOL();
  1416. serial_delay(25);
  1417. SERIAL_ECHOLNPAIR("EEPROM free for UBL: ", hex_address((void*)(settings.meshes_end_index() - settings.meshes_start_index())));
  1418. serial_delay(50);
  1419. SERIAL_ECHOLNPAIR("EEPROM can hold ", settings.calc_num_meshes(), " meshes.\n");
  1420. serial_delay(25);
  1421. #endif // UBL_DEVEL_DEBUGGING
  1422. if (!sanity_check()) {
  1423. echo_name();
  1424. SERIAL_ECHOLNPGM(" sanity checks passed.");
  1425. }
  1426. }
  1427. /**
  1428. * When we are fully debugged, the EEPROM dump command will get deleted also. But
  1429. * right now, it is good to have the extra information. Soon... we prune this.
  1430. */
  1431. void unified_bed_leveling::g29_eeprom_dump() {
  1432. uint8_t cccc;
  1433. SERIAL_ECHO_MSG("EEPROM Dump:");
  1434. persistentStore.access_start();
  1435. for (uint16_t i = 0; i < persistentStore.capacity(); i += 16) {
  1436. if (!(i & 0x3)) idle();
  1437. print_hex_word(i);
  1438. SERIAL_ECHOPGM(": ");
  1439. for (uint16_t j = 0; j < 16; j++) {
  1440. persistentStore.read_data(i + j, &cccc, sizeof(uint8_t));
  1441. print_hex_byte(cccc);
  1442. SERIAL_CHAR(' ');
  1443. }
  1444. SERIAL_EOL();
  1445. }
  1446. SERIAL_EOL();
  1447. persistentStore.access_finish();
  1448. }
  1449. /**
  1450. * When we are fully debugged, this may go away. But there are some valid
  1451. * use cases for the users. So we can wait and see what to do with it.
  1452. */
  1453. void unified_bed_leveling::g29_compare_current_mesh_to_stored_mesh() {
  1454. int16_t a = settings.calc_num_meshes();
  1455. if (!a) {
  1456. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  1457. return;
  1458. }
  1459. if (!parser.has_value()) {
  1460. SERIAL_ECHOLNPAIR("?Storage slot # required.\n?Use 0 to ", a - 1);
  1461. return;
  1462. }
  1463. g29_storage_slot = parser.value_int();
  1464. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  1465. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  1466. return;
  1467. }
  1468. float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  1469. settings.load_mesh(g29_storage_slot, &tmp_z_values);
  1470. SERIAL_ECHOLNPAIR("Subtracting mesh in slot ", g29_storage_slot, " from current mesh.");
  1471. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  1472. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  1473. z_values[x][y] -= tmp_z_values[x][y];
  1474. }
  1475. #endif // UBL_DEVEL_DEBUGGING
  1476. #endif // AUTO_BED_LEVELING_UBL