My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ubl_G29.cpp 72KB

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