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

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