My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ubl_G29.cpp 75KB

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