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

ubl_G29.cpp 75KB

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