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

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