My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ubl_G29.cpp 75KB

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