My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ubl_G29.cpp 75KB

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