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

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