My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ubl_G29.cpp 78KB

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