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

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