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

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