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 70KB

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