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

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