My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ubl_G29.cpp 70KB

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