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

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