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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2019 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 "../../../inc/MarlinConfig.h"
  23. #if ENABLED(AUTO_BED_LEVELING_UBL)
  24. //#define UBL_DEVEL_DEBUGGING
  25. #include "ubl.h"
  26. #include "../../../Marlin.h"
  27. #include "../../../HAL/shared/persistent_store_api.h"
  28. #include "../../../libs/hex_print_routines.h"
  29. #include "../../../module/configuration_store.h"
  30. #include "../../../lcd/ultralcd.h"
  31. #include "../../../module/stepper.h"
  32. #include "../../../module/planner.h"
  33. #include "../../../module/probe.h"
  34. #include "../../../gcode/gcode.h"
  35. #include "../../../core/serial.h"
  36. #include "../../../gcode/parser.h"
  37. #include "../../../feature/bedlevel/bedlevel.h"
  38. #include "../../../libs/least_squares_fit.h"
  39. #if ENABLED(DUAL_X_CARRIAGE)
  40. #include "../../../module/tool_change.h"
  41. #endif
  42. #include <math.h>
  43. #define UBL_G29_P31
  44. extern float destination[XYZE], current_position[XYZE];
  45. #if HAS_LCD_MENU
  46. void _lcd_ubl_output_map_lcd();
  47. #endif
  48. #define SIZE_OF_LITTLE_RAISE 1
  49. #define BIG_RAISE_NOT_NEEDED 0
  50. int unified_bed_leveling::g29_verbose_level,
  51. unified_bed_leveling::g29_phase_value,
  52. unified_bed_leveling::g29_repetition_cnt,
  53. unified_bed_leveling::g29_storage_slot = 0,
  54. unified_bed_leveling::g29_map_type;
  55. bool unified_bed_leveling::g29_c_flag,
  56. unified_bed_leveling::g29_x_flag,
  57. unified_bed_leveling::g29_y_flag;
  58. float unified_bed_leveling::g29_x_pos,
  59. unified_bed_leveling::g29_y_pos,
  60. unified_bed_leveling::g29_card_thickness = 0,
  61. unified_bed_leveling::g29_constant = 0;
  62. #if HAS_BED_PROBE
  63. int unified_bed_leveling::g29_grid_size;
  64. #endif
  65. /**
  66. * G29: Unified Bed Leveling by Roxy
  67. *
  68. * Parameters understood by this leveling system:
  69. *
  70. * A Activate Activate the Unified Bed Leveling system.
  71. *
  72. * B # Business Use the 'Business Card' mode of the Manual Probe subsystem with P2.
  73. * Note: A non-compressible Spark Gap feeler gauge is recommended over a business card.
  74. * In this mode of G29 P2, a business or index card is used as a shim that the nozzle can
  75. * grab onto as it is lowered. In principle, the nozzle-bed distance is the same when the
  76. * same resistance is felt in the shim. You can omit the numerical value on first invocation
  77. * of G29 P2 B to measure shim thickness. Subsequent use of 'B' will apply the previously-
  78. * measured thickness by default.
  79. *
  80. * C Continue G29 P1 C continues the generation of a partially-constructed Mesh without invalidating
  81. * previous measurements.
  82. *
  83. * C G29 P2 C tells the Manual Probe subsystem to not use the current nozzle
  84. * location in its search for the closest unmeasured Mesh Point. Instead, attempt to
  85. * start at one end of the uprobed points and Continue sequentially.
  86. *
  87. * G29 P3 C specifies the Constant for the fill. Otherwise, uses a "reasonable" value.
  88. *
  89. * C Current G29 Z C uses the Current location (instead of bed center or nearest edge).
  90. *
  91. * D Disable Disable the Unified Bed Leveling system.
  92. *
  93. * E Stow_probe Stow the probe after each sampled point.
  94. *
  95. * F # Fade Fade the amount of Mesh Based Compensation over a specified height. At the
  96. * specified height, no correction is applied and natural printer kenimatics take over. If no
  97. * number is specified for the command, 10mm is assumed to be reasonable.
  98. *
  99. * H # Height With P2, 'H' specifies the Height to raise the nozzle after each manual probe of the bed.
  100. * If omitted, the nozzle will raise by Z_CLEARANCE_BETWEEN_PROBES.
  101. *
  102. * H # Offset With P4, 'H' specifies the Offset above the mesh height to place the nozzle.
  103. * If omitted, Z_CLEARANCE_BETWEEN_PROBES will be used.
  104. *
  105. * I # Invalidate Invalidate the specified number of Mesh Points near the given 'X' 'Y'. If X or Y are omitted,
  106. * the nozzle location is used. If no 'I' value is given, only the point nearest to the location
  107. * is invalidated. Use 'T' to produce a map afterward. This command is useful to invalidate a
  108. * portion of the Mesh so it can be adjusted using other UBL tools. When attempting to invalidate
  109. * an isolated bad mesh point, the 'T' option shows the nozzle position in the Mesh with (#). You
  110. * can move the nozzle around and use this feature to select the center of the area (or cell) to
  111. * invalidate.
  112. *
  113. * J # Grid Perform a Grid Based Leveling of the current Mesh using a grid with n points on a side.
  114. * Not specifying a grid size will invoke the 3-Point leveling function.
  115. *
  116. * L Load Load Mesh from the previously activated location in the EEPROM.
  117. *
  118. * L # Load Load Mesh from the specified location in the EEPROM. Set this location as activated
  119. * for subsequent Load and Store operations.
  120. *
  121. * The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will
  122. * start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with
  123. * each additional Phase that processes it.
  124. *
  125. * P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the
  126. * 3D Printer to the same state it was in before the Unified Bed Leveling Compensation
  127. * was turned on. Setting the entire Mesh to Zero is a special case that allows
  128. * a subsequent G or T leveling operation for backward compatibility.
  129. *
  130. * P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using
  131. * the Z-Probe. Usually the probe can't reach all areas that the nozzle can reach. For delta
  132. * printers only the areas where the probe and nozzle can both reach will be automatically probed.
  133. *
  134. * Unreachable points will be handled in Phase 2 and Phase 3.
  135. *
  136. * Use 'C' to leave the previous mesh intact and automatically probe needed points. This allows you
  137. * to invalidate parts of the Mesh but still use Automatic Probing.
  138. *
  139. * The 'X' and 'Y' parameters prioritize where to try and measure points. If omitted, the current
  140. * probe position is used.
  141. *
  142. * Use 'T' (Topology) to generate a report of mesh generation.
  143. *
  144. * P1 will suspend Mesh generation if the controller button is held down. Note that you may need
  145. * to press and hold the switch for several seconds if moves are underway.
  146. *
  147. * P2 Phase 2 Probe unreachable points.
  148. *
  149. * Use 'H' to set the height between Mesh points. If omitted, Z_CLEARANCE_BETWEEN_PROBES is used.
  150. * Smaller values will be quicker. Move the nozzle down till it barely touches the bed. Make sure the
  151. * nozzle is clean and unobstructed. Use caution and move slowly. This can damage your printer!
  152. * (Uses SIZE_OF_LITTLE_RAISE mm if the nozzle is moving less than BIG_RAISE_NOT_NEEDED mm.)
  153. *
  154. * The 'H' value can be negative if the Mesh dips in a large area. Press and hold the
  155. * controller button to terminate the current Phase 2 command. You can then re-issue "G29 P 2"
  156. * with an 'H' parameter more suitable for the area you're manually probing. Note that the command
  157. * tries to start in a corner of the bed where movement will be predictable. Override the distance
  158. * calculation location with the X and Y parameters. You can print a Mesh Map (G29 T) to see where
  159. * the mesh is invalidated and where the nozzle needs to move to complete the command. Use 'C' to
  160. * indicate that the search should be based on the current position.
  161. *
  162. * The 'B' parameter for this command is described above. It places the manual probe subsystem into
  163. * Business Card mode where the thickness of a business card is measured and then used to accurately
  164. * set the nozzle height in all manual probing for the duration of the command. A Business card can
  165. * be used, but you'll get better results with a flexible Shim that doesn't compress. This makes it
  166. * easier to produce similar amounts of force and get more accurate measurements. Google if you're
  167. * not sure how to use a shim.
  168. *
  169. * The 'T' (Map) parameter helps track Mesh building progress.
  170. *
  171. * NOTE: P2 requires an LCD controller!
  172. *
  173. * P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. There are two different paths to
  174. * go down:
  175. *
  176. * - If a 'C' constant is specified, the closest invalid mesh points to the nozzle will be filled,
  177. * and a repeat count can then also be specified with 'R'.
  178. *
  179. * - Leaving out 'C' invokes Smart Fill, which scans the mesh from the edges inward looking for
  180. * invalid mesh points. Adjacent points are used to determine the bed slope. If the bed is sloped
  181. * upward from the invalid point, it takes the value of the nearest point. If sloped downward, it's
  182. * replaced by a value that puts all three points in a line. This version of G29 P3 is a quick, easy
  183. * and (usually) safe way to populate unprobed mesh regions before continuing to G26 Mesh Validation
  184. * Pattern. Note that this populates the mesh with unverified values. Pay attention and use caution.
  185. *
  186. * P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assumes the existence of
  187. * an LCD Panel. It is possible to fine tune the mesh without an LCD Panel using
  188. * G42 and M421. See the UBL documentation for further details.
  189. *
  190. * Phase 4 is meant to be used with G26 Mesh Validation to fine tune the mesh by direct editing
  191. * of Mesh Points. Raise and lower points to fine tune the mesh until it gives consistently reliable
  192. * adhesion.
  193. *
  194. * P4 moves to the closest Mesh Point (and/or the given X Y), raises the nozzle above the mesh height
  195. * by the given 'H' offset (or default 0), and waits while the controller is used to adjust the nozzle
  196. * height. On click the displayed height is saved in the mesh.
  197. *
  198. * Start Phase 4 at a specific location with X and Y. Adjust a specific number of Mesh Points with
  199. * the 'R' (Repeat) parameter. (If 'R' is left out, the whole matrix is assumed.) This command can be
  200. * terminated early (e.g., after editing the area of interest) by pressing and holding the encoder button.
  201. *
  202. * The general form is G29 P4 [R points] [X position] [Y position]
  203. *
  204. * The H [offset] parameter is useful if a shim is used to fine-tune the mesh. For a 0.4mm shim the
  205. * command would be G29 P4 H0.4. The nozzle is moved to the shim height, you adjust height to the shim,
  206. * and on click the height minus the shim thickness will be saved in the mesh.
  207. *
  208. * !!Use with caution, as a very poor mesh could cause the nozzle to crash into the bed!!
  209. *
  210. * NOTE: P4 is not available unless you have LCD support enabled!
  211. *
  212. * P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and
  213. * work with the Mesh if it is Mean Adjusted. You can specify a C parameter to
  214. * Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically
  215. * execute a G29 P6 C <mean height>.
  216. *
  217. * P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified
  218. * with the C parameter. Being able to adjust the height of a Mesh is useful tool. It
  219. * can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally,
  220. * you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring
  221. * 0.000 at the Z Home location.
  222. *
  223. * Q Test Load specified Test Pattern to assist in checking correct operation of system. This
  224. * command is not anticipated to be of much value to the typical user. It is intended
  225. * for developers to help them verify correct operation of the Unified Bed Leveling System.
  226. *
  227. * R # Repeat Repeat this command the specified number of times. If no number is specified the
  228. * command will be repeated GRID_MAX_POINTS_X * GRID_MAX_POINTS_Y times.
  229. *
  230. * S Store Store the current Mesh in the Activated area of the EEPROM. It will also store the
  231. * current state of the Unified Bed Leveling system in the EEPROM.
  232. *
  233. * S # Store Store the current Mesh at the specified location in EEPROM. Activate this location
  234. * for subsequent Load and Store operations. Valid storage slot numbers begin at 0 and
  235. * extend to a limit related to the available EEPROM storage.
  236. *
  237. * S -1 Store Print the current Mesh as G-code that can be used to restore the mesh anytime.
  238. *
  239. * T Topology Display the Mesh Map Topology.
  240. * 'T' can be used alone (e.g., G29 T) or in combination with most of the other commands.
  241. * This option works with all Phase commands (e.g., G29 P4 R 5 T X 50 Y100 C -.1 O)
  242. * This parameter can also specify a Map Type. T0 (the default) is user-readable. T1 can
  243. * is suitable to paste into a spreadsheet for a 3D graph of the mesh.
  244. *
  245. * U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds.
  246. * Only used for G29 P1 T U. This speeds up the probing of the edge of the bed. Useful
  247. * when the entire bed doesn't need to be probed because it will be adjusted.
  248. *
  249. * V # Verbosity Set the verbosity level (0-4) for extra details. (Default 0)
  250. *
  251. * X # X Location for this command
  252. *
  253. * Y # Y Location for this command
  254. *
  255. * With UBL_DEVEL_DEBUGGING:
  256. *
  257. * K # Kompare Kompare current Mesh with stored Mesh #, replacing current Mesh with the result.
  258. * This command literally performs a diff between two Meshes.
  259. *
  260. * Q-1 Dump EEPROM Dump the UBL contents stored in EEPROM as HEX format. Useful for developers to help
  261. * verify correct operation of the UBL.
  262. *
  263. * W What? Display valuable UBL data.
  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 required.
  269. *
  270. * When you do a G28 and G29 P1 to automatically build your first mesh, you are going to notice that
  271. * UBL probes points increasingly further from the starting location. (The starting location defaults
  272. * to the center of the bed.) In contrast, ABL and MBL follow a zigzag pattern. The spiral pattern is
  273. * especially better for Delta printers, since it populates the center of the mesh first, allowing for
  274. * a quicker test print to verify settings. You don't need to populate the entire mesh to use it.
  275. * After all, you don't want to spend a lot of time generating a mesh only to realize the resolution
  276. * or zprobe_zoffset are incorrect. Mesh-generation gathers points starting closest to the nozzle unless
  277. * an (X,Y) coordinate pair is given.
  278. *
  279. * Unified Bed Leveling uses a lot of EEPROM storage to hold its data, and it takes some effort to get
  280. * the mesh just right. To prevent this valuable data from being destroyed as the EEPROM structure
  281. * evolves, UBL stores all mesh data at the end of EEPROM.
  282. *
  283. * UBL is founded on Edward Patel's Mesh Bed Leveling code. A big 'Thanks!' to him and the creators of
  284. * 3-Point and Grid Based leveling. Combining their contributions we now have the functionality and
  285. * features of all three systems combined.
  286. */
  287. void unified_bed_leveling::G29() {
  288. if (g29_parameter_parsing()) return; // Abort on parameter error
  289. const int8_t p_val = parser.intval('P', -1);
  290. const bool may_move = p_val == 1 || p_val == 2 || p_val == 4 || parser.seen('J');
  291. // Check for commands that require the printer to be homed
  292. if (may_move) {
  293. if (axis_unhomed_error()) gcode.home_all_axes();
  294. #if ENABLED(DUAL_X_CARRIAGE)
  295. if (active_extruder != 0) tool_change(0);
  296. #endif
  297. }
  298. // Invalidate Mesh Points. This command is a little bit asymmetrical because
  299. // it directly specifies the repetition count and does not use the 'R' parameter.
  300. if (parser.seen('I')) {
  301. uint8_t cnt = 0;
  302. g29_repetition_cnt = parser.has_value() ? parser.value_int() : 1;
  303. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  304. set_all_mesh_points_to_value(NAN);
  305. }
  306. else {
  307. while (g29_repetition_cnt--) {
  308. if (cnt > 20) { cnt = 0; idle(); }
  309. const mesh_index_pair location = find_closest_mesh_point_of_type(REAL, g29_x_pos, g29_y_pos, USE_NOZZLE_AS_REFERENCE, NULL);
  310. if (location.x_index < 0) {
  311. // No more REACHABLE mesh points to invalidate, so we ASSUME the user
  312. // meant to invalidate the ENTIRE mesh, which cannot be done with
  313. // find_closest_mesh_point loop which only returns REACHABLE points.
  314. set_all_mesh_points_to_value(NAN);
  315. SERIAL_ECHOLNPGM("Entire Mesh invalidated.\n");
  316. break; // No more invalid Mesh Points to populate
  317. }
  318. z_values[location.x_index][location.y_index] = NAN;
  319. #if ENABLED(EXTENSIBLE_UI)
  320. ExtUI::onMeshUpdate(location.x_index, location.y_index, 0);
  321. #endif
  322. cnt++;
  323. }
  324. }
  325. SERIAL_ECHOLNPGM("Locations invalidated.\n");
  326. }
  327. if (parser.seen('Q')) {
  328. const int test_pattern = parser.has_value() ? parser.value_int() : -99;
  329. if (!WITHIN(test_pattern, -1, 2)) {
  330. SERIAL_ECHOLNPGM("Invalid test_pattern value. (-1 to 2)\n");
  331. return;
  332. }
  333. SERIAL_ECHOLNPGM("Loading test_pattern values.\n");
  334. switch (test_pattern) {
  335. #if ENABLED(UBL_DEVEL_DEBUGGING)
  336. case -1:
  337. g29_eeprom_dump();
  338. break;
  339. #endif
  340. case 0:
  341. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) { // Create a bowl shape - similar to
  342. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++) { // a poorly calibrated Delta.
  343. const float p1 = 0.5f * (GRID_MAX_POINTS_X) - x,
  344. p2 = 0.5f * (GRID_MAX_POINTS_Y) - y;
  345. z_values[x][y] += 2.0f * HYPOT(p1, p2);
  346. #if ENABLED(EXTENSIBLE_UI)
  347. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  348. #endif
  349. }
  350. }
  351. break;
  352. case 1:
  353. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) { // Create a diagonal line several Mesh cells thick that is raised
  354. z_values[x][x] += 9.999f;
  355. z_values[x][x + (x < GRID_MAX_POINTS_Y - 1) ? 1 : -1] += 9.999f; // We want the altered line several mesh points thick
  356. #if ENABLED(EXTENSIBLE_UI)
  357. ExtUI::onMeshUpdate(x, x, z_values[x][x]);
  358. ExtUI::onMeshUpdate(x, (x + (x < GRID_MAX_POINTS_Y - 1) ? 1 : -1), z_values[x][x + (x < GRID_MAX_POINTS_Y - 1) ? 1 : -1]);
  359. #endif
  360. }
  361. break;
  362. case 2:
  363. // Allow the user to specify the height because 10mm is a little extreme in some cases.
  364. for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in
  365. for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) // the center of the bed
  366. z_values[x][y] += parser.seen('C') ? g29_constant : 9.99f;
  367. #if ENABLED(EXTENSIBLE_UI)
  368. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  369. #endif
  370. break;
  371. }
  372. }
  373. #if HAS_BED_PROBE
  374. if (parser.seen('J')) {
  375. if (g29_grid_size) { // if not 0 it is a normal n x n grid being probed
  376. save_ubl_active_state_and_disable();
  377. tilt_mesh_based_on_probed_grid(false /* false says to do normal grid probing */ );
  378. restore_ubl_active_state_and_leave();
  379. }
  380. else { // grid_size == 0 : A 3-Point leveling has been requested
  381. save_ubl_active_state_and_disable();
  382. tilt_mesh_based_on_probed_grid(true /* true says to do 3-Point leveling */ );
  383. restore_ubl_active_state_and_leave();
  384. }
  385. do_blocking_move_to_xy(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)));
  386. report_current_position();
  387. }
  388. #endif // HAS_BED_PROBE
  389. if (parser.seen('P')) {
  390. if (WITHIN(g29_phase_value, 0, 1) && storage_slot == -1) {
  391. storage_slot = 0;
  392. SERIAL_ECHOLNPGM("Default storage slot 0 selected.");
  393. }
  394. switch (g29_phase_value) {
  395. case 0:
  396. //
  397. // Zero Mesh Data
  398. //
  399. reset();
  400. SERIAL_ECHOLNPGM("Mesh zeroed.");
  401. break;
  402. #if HAS_BED_PROBE
  403. case 1:
  404. //
  405. // Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
  406. //
  407. if (!parser.seen('C')) {
  408. invalidate();
  409. SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh.");
  410. }
  411. if (g29_verbose_level > 1) {
  412. SERIAL_ECHOPAIR("Probing Mesh Points Closest to (", g29_x_pos);
  413. SERIAL_CHAR(',');
  414. SERIAL_ECHO(g29_y_pos);
  415. SERIAL_ECHOLNPGM(").\n");
  416. }
  417. probe_entire_mesh(g29_x_pos + X_PROBE_OFFSET_FROM_EXTRUDER, g29_y_pos + Y_PROBE_OFFSET_FROM_EXTRUDER,
  418. parser.seen('T'), parser.seen('E'), parser.seen('U'));
  419. report_current_position();
  420. break;
  421. #endif // HAS_BED_PROBE
  422. case 2: {
  423. #if HAS_LCD_MENU
  424. //
  425. // Manually Probe Mesh in areas that can't be reached by the probe
  426. //
  427. SERIAL_ECHOLNPGM("Manually probing unreachable mesh locations.");
  428. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  429. if (parser.seen('C') && !g29_x_flag && !g29_y_flag) {
  430. /**
  431. * Use a good default location for the path.
  432. * The flipped > and < operators in these comparisons is intentional.
  433. * It should cause the probed points to follow a nice path on Cartesian printers.
  434. * It may make sense to have Delta printers default to the center of the bed.
  435. * Until that is decided, this can be forced with the X and Y parameters.
  436. */
  437. #if IS_KINEMATIC
  438. g29_x_pos = X_HOME_POS;
  439. g29_y_pos = Y_HOME_POS;
  440. #else // cartesian
  441. g29_x_pos = X_PROBE_OFFSET_FROM_EXTRUDER > 0 ? X_BED_SIZE : 0;
  442. g29_y_pos = Y_PROBE_OFFSET_FROM_EXTRUDER < 0 ? Y_BED_SIZE : 0;
  443. #endif
  444. }
  445. if (parser.seen('B')) {
  446. g29_card_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness((float) Z_CLEARANCE_BETWEEN_PROBES);
  447. if (ABS(g29_card_thickness) > 1.5f) {
  448. SERIAL_ECHOLNPGM("?Error in Business Card measurement.");
  449. return;
  450. }
  451. }
  452. if (!position_is_reachable(g29_x_pos, g29_y_pos)) {
  453. SERIAL_ECHOLNPGM("XY outside printable radius.");
  454. return;
  455. }
  456. const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES);
  457. manually_probe_remaining_mesh(g29_x_pos, g29_y_pos, height, g29_card_thickness, parser.seen('T'));
  458. SERIAL_ECHOLNPGM("G29 P2 finished.");
  459. report_current_position();
  460. #else
  461. SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present.");
  462. return;
  463. #endif
  464. } break;
  465. case 3: {
  466. /**
  467. * Populate invalid mesh areas. Proceed with caution.
  468. * Two choices are available:
  469. * - Specify a constant with the 'C' parameter.
  470. * - Allow 'G29 P3' to choose a 'reasonable' constant.
  471. */
  472. if (g29_c_flag) {
  473. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  474. set_all_mesh_points_to_value(g29_constant);
  475. }
  476. else {
  477. while (g29_repetition_cnt--) { // this only populates reachable mesh points near
  478. const mesh_index_pair location = find_closest_mesh_point_of_type(INVALID, g29_x_pos, g29_y_pos, USE_NOZZLE_AS_REFERENCE, NULL);
  479. if (location.x_index < 0) {
  480. // No more REACHABLE INVALID mesh points to populate, so we ASSUME
  481. // user meant to populate ALL INVALID mesh points to value
  482. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  483. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  484. if (isnan(z_values[x][y]))
  485. z_values[x][y] = g29_constant;
  486. break; // No more invalid Mesh Points to populate
  487. }
  488. z_values[location.x_index][location.y_index] = g29_constant;
  489. #if ENABLED(EXTENSIBLE_UI)
  490. ExtUI::onMeshUpdate(location.x_index, location.y_index, z_values[location.x_index][location.y_index]);
  491. #endif
  492. }
  493. }
  494. }
  495. else {
  496. const float cvf = parser.value_float();
  497. switch ((int)truncf(cvf * 10.0f) - 30) { // 3.1 -> 1
  498. #if ENABLED(UBL_G29_P31)
  499. case 1: {
  500. // P3.1 use least squares fit to fill missing mesh values
  501. // P3.10 zero weighting for distance, all grid points equal, best fit tilted plane
  502. // P3.11 10X weighting for nearest grid points versus farthest grid points
  503. // P3.12 100X distance weighting
  504. // P3.13 1000X distance weighting, approaches simple average of nearest points
  505. const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345
  506. weight_factor = weight_power ? POW(10.0f, weight_power) : 0;
  507. smart_fill_wlsf(weight_factor);
  508. }
  509. break;
  510. #endif
  511. case 0: // P3 or P3.0
  512. default: // and anything P3.x that's not P3.1
  513. smart_fill_mesh(); // Do a 'Smart' fill using nearby known values
  514. break;
  515. }
  516. }
  517. break;
  518. }
  519. case 4: // Fine Tune (i.e., Edit) the Mesh
  520. #if HAS_LCD_MENU
  521. fine_tune_mesh(g29_x_pos, g29_y_pos, parser.seen('T'));
  522. #else
  523. SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present.");
  524. return;
  525. #endif
  526. break;
  527. case 5: adjust_mesh_to_mean(g29_c_flag, g29_constant); break;
  528. case 6: shift_mesh_height(); break;
  529. }
  530. }
  531. #if ENABLED(UBL_DEVEL_DEBUGGING)
  532. //
  533. // Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  534. // good to have the extra information. Soon... we prune this to just a few items
  535. //
  536. if (parser.seen('W')) g29_what_command();
  537. //
  538. // When we are fully debugged, this may go away. But there are some valid
  539. // use cases for the users. So we can wait and see what to do with it.
  540. //
  541. if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
  542. g29_compare_current_mesh_to_stored_mesh();
  543. #endif // UBL_DEVEL_DEBUGGING
  544. //
  545. // Load a Mesh from the EEPROM
  546. //
  547. if (parser.seen('L')) { // Load Current Mesh Data
  548. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  549. int16_t a = settings.calc_num_meshes();
  550. if (!a) {
  551. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  552. return;
  553. }
  554. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  555. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  556. return;
  557. }
  558. settings.load_mesh(g29_storage_slot);
  559. storage_slot = g29_storage_slot;
  560. SERIAL_ECHOLNPGM("Done.");
  561. }
  562. //
  563. // Store a Mesh in the EEPROM
  564. //
  565. if (parser.seen('S')) { // Store (or Save) Current Mesh Data
  566. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  567. if (g29_storage_slot == -1) // Special case, the user wants to 'Export' the mesh to the
  568. return report_current_mesh(); // host program to be saved on the user's computer
  569. int16_t a = settings.calc_num_meshes();
  570. if (!a) {
  571. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  572. goto LEAVE;
  573. }
  574. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  575. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  576. goto LEAVE;
  577. }
  578. settings.store_mesh(g29_storage_slot);
  579. storage_slot = g29_storage_slot;
  580. SERIAL_ECHOLNPGM("Done.");
  581. }
  582. if (parser.seen('T'))
  583. display_map(g29_map_type);
  584. LEAVE:
  585. #if HAS_LCD_MENU
  586. ui.reset_alert_level();
  587. ui.quick_feedback();
  588. ui.reset_status();
  589. ui.release();
  590. #endif
  591. return;
  592. }
  593. void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const float value) {
  594. float sum = 0;
  595. int n = 0;
  596. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  597. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  598. if (!isnan(z_values[x][y])) {
  599. sum += z_values[x][y];
  600. n++;
  601. }
  602. const float mean = sum / n;
  603. //
  604. // Sum the squares of difference from mean
  605. //
  606. float sum_of_diff_squared = 0;
  607. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  608. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  609. if (!isnan(z_values[x][y]))
  610. sum_of_diff_squared += sq(z_values[x][y] - mean);
  611. SERIAL_ECHOLNPAIR("# of samples: ", n);
  612. SERIAL_ECHOLNPAIR_F("Mean Mesh Height: ", mean, 6);
  613. const float sigma = SQRT(sum_of_diff_squared / (n + 1));
  614. SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6);
  615. if (cflag)
  616. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  617. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  618. if (!isnan(z_values[x][y])) {
  619. z_values[x][y] -= mean + value;
  620. #if ENABLED(EXTENSIBLE_UI)
  621. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  622. #endif
  623. }
  624. }
  625. void unified_bed_leveling::shift_mesh_height() {
  626. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  627. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  628. if (!isnan(z_values[x][y])) {
  629. z_values[x][y] += g29_constant;
  630. #if ENABLED(EXTENSIBLE_UI)
  631. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  632. #endif
  633. }
  634. }
  635. #if HAS_BED_PROBE
  636. /**
  637. * Probe all invalidated locations of the mesh that can be reached by the probe.
  638. * This attempts to fill in locations closest to the nozzle's start location first.
  639. */
  640. void unified_bed_leveling::probe_entire_mesh(const float &rx, const float &ry, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) {
  641. mesh_index_pair location;
  642. #if HAS_LCD_MENU
  643. ui.capture();
  644. #endif
  645. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  646. DEPLOY_PROBE();
  647. uint16_t count = GRID_MAX_POINTS;
  648. do {
  649. if (do_ubl_mesh_map) display_map(g29_map_type);
  650. #if HAS_LCD_MENU
  651. if (ui.button_pressed()) {
  652. ui.quick_feedback(false); // Preserve button state for click-and-hold
  653. SERIAL_ECHOLNPGM("\nMesh only partially populated.\n");
  654. STOW_PROBE();
  655. ui.wait_for_release();
  656. ui.quick_feedback();
  657. ui.release();
  658. restore_ubl_active_state_and_leave();
  659. return;
  660. }
  661. #endif
  662. if (do_furthest)
  663. location = find_furthest_invalid_mesh_point();
  664. else
  665. location = find_closest_mesh_point_of_type(INVALID, rx, ry, USE_PROBE_AS_REFERENCE, NULL);
  666. if (location.x_index >= 0) { // mesh point found and is reachable by probe
  667. const float rawx = mesh_index_to_xpos(location.x_index),
  668. rawy = mesh_index_to_ypos(location.y_index);
  669. const float measured_z = probe_pt(rawx, rawy, stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level); // TODO: Needs error handling
  670. z_values[location.x_index][location.y_index] = measured_z;
  671. #if ENABLED(EXTENSIBLE_UI)
  672. ExtUI::onMeshUpdate(location.x_index, location.y_index, measured_z);
  673. #endif
  674. }
  675. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  676. } while (location.x_index >= 0 && --count);
  677. STOW_PROBE();
  678. #ifdef Z_AFTER_PROBING
  679. move_z_after_probing();
  680. #endif
  681. restore_ubl_active_state_and_leave();
  682. do_blocking_move_to_xy(
  683. constrain(rx - (X_PROBE_OFFSET_FROM_EXTRUDER), MESH_MIN_X, MESH_MAX_X),
  684. constrain(ry - (Y_PROBE_OFFSET_FROM_EXTRUDER), MESH_MIN_Y, MESH_MAX_Y)
  685. );
  686. }
  687. #endif // HAS_BED_PROBE
  688. #if HAS_LCD_MENU
  689. typedef void (*clickFunc_t)();
  690. bool click_and_hold(const clickFunc_t func=NULL) {
  691. if (ui.button_pressed()) {
  692. ui.quick_feedback(false); // Preserve button state for click-and-hold
  693. const millis_t nxt = millis() + 1500UL;
  694. while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag!
  695. idle(); // idle, of course
  696. if (ELAPSED(millis(), nxt)) { // After 1.5 seconds
  697. ui.quick_feedback();
  698. if (func) (*func)();
  699. ui.wait_for_release();
  700. return true;
  701. }
  702. }
  703. }
  704. serial_delay(15);
  705. return false;
  706. }
  707. void unified_bed_leveling::move_z_with_encoder(const float &multiplier) {
  708. ui.wait_for_release();
  709. while (!ui.button_pressed()) {
  710. idle();
  711. gcode.reset_stepper_timeout(); // Keep steppers powered
  712. if (encoder_diff) {
  713. do_blocking_move_to_z(current_position[Z_AXIS] + float(encoder_diff) * multiplier);
  714. encoder_diff = 0;
  715. }
  716. }
  717. }
  718. float unified_bed_leveling::measure_point_with_encoder() {
  719. KEEPALIVE_STATE(PAUSED_FOR_USER);
  720. move_z_with_encoder(0.01f);
  721. KEEPALIVE_STATE(IN_HANDLER);
  722. return current_position[Z_AXIS];
  723. }
  724. static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); }
  725. float unified_bed_leveling::measure_business_card_thickness(float in_height) {
  726. ui.capture();
  727. save_ubl_active_state_and_disable(); // Disable bed level correction for probing
  728. do_blocking_move_to(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)), in_height);
  729. //, MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f);
  730. planner.synchronize();
  731. SERIAL_ECHOPGM("Place shim under nozzle");
  732. LCD_MESSAGEPGM(MSG_UBL_BC_INSERT);
  733. ui.return_to_status();
  734. echo_and_take_a_measurement();
  735. const float z1 = measure_point_with_encoder();
  736. do_blocking_move_to_z(current_position[Z_AXIS] + SIZE_OF_LITTLE_RAISE);
  737. planner.synchronize();
  738. SERIAL_ECHOPGM("Remove shim");
  739. LCD_MESSAGEPGM(MSG_UBL_BC_REMOVE);
  740. echo_and_take_a_measurement();
  741. const float z2 = measure_point_with_encoder();
  742. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_BETWEEN_PROBES);
  743. const float thickness = ABS(z1 - z2);
  744. if (g29_verbose_level > 1) {
  745. SERIAL_ECHOPAIR_F("Business Card is ", thickness, 4);
  746. SERIAL_ECHOLNPGM("mm thick.");
  747. }
  748. ui.release();
  749. restore_ubl_active_state_and_leave();
  750. return thickness;
  751. }
  752. void abort_manual_probe_remaining_mesh() {
  753. SERIAL_ECHOLNPGM("\nMesh only partially populated.");
  754. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  755. ui.release();
  756. KEEPALIVE_STATE(IN_HANDLER);
  757. ui.quick_feedback();
  758. ubl.restore_ubl_active_state_and_leave();
  759. }
  760. void unified_bed_leveling::manually_probe_remaining_mesh(const float &rx, const float &ry, const float &z_clearance, const float &thick, const bool do_ubl_mesh_map) {
  761. ui.capture();
  762. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  763. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_clearance);
  764. ui.return_to_status();
  765. mesh_index_pair location;
  766. do {
  767. location = find_closest_mesh_point_of_type(INVALID, rx, ry, USE_NOZZLE_AS_REFERENCE, NULL);
  768. // It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
  769. if (location.x_index < 0 && location.y_index < 0) continue;
  770. const float xProbe = mesh_index_to_xpos(location.x_index),
  771. yProbe = mesh_index_to_ypos(location.y_index);
  772. if (!position_is_reachable(xProbe, yProbe)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points)
  773. LCD_MESSAGEPGM(MSG_UBL_MOVING_TO_NEXT);
  774. do_blocking_move_to(xProbe, yProbe, Z_CLEARANCE_BETWEEN_PROBES);
  775. do_blocking_move_to_z(z_clearance);
  776. KEEPALIVE_STATE(PAUSED_FOR_USER);
  777. ui.capture();
  778. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  779. serialprintPGM(parser.seen('B') ? PSTR(MSG_UBL_BC_INSERT) : PSTR(MSG_UBL_BC_INSERT2));
  780. const float z_step = 0.01f; // existing behavior: 0.01mm per click, occasionally step
  781. //const float z_step = planner.steps_to_mm[Z_AXIS]; // approx one step each click
  782. move_z_with_encoder(z_step);
  783. if (click_and_hold()) {
  784. SERIAL_ECHOLNPGM("\nMesh only partially populated.");
  785. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  786. ui.release();
  787. KEEPALIVE_STATE(IN_HANDLER);
  788. restore_ubl_active_state_and_leave();
  789. return;
  790. }
  791. z_values[location.x_index][location.y_index] = current_position[Z_AXIS] - thick;
  792. #if ENABLED(EXTENSIBLE_UI)
  793. ExtUI::onMeshUpdate(location.x_index, location.y_index, z_values[location.x_index][location.y_index]);
  794. #endif
  795. if (g29_verbose_level > 2)
  796. SERIAL_ECHOLNPAIR_F("Mesh Point Measured at: ", z_values[location.x_index][location.y_index], 6);
  797. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  798. } while (location.x_index >= 0 && location.y_index >= 0);
  799. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  800. restore_ubl_active_state_and_leave();
  801. KEEPALIVE_STATE(IN_HANDLER);
  802. do_blocking_move_to(rx, ry, Z_CLEARANCE_DEPLOY_PROBE);
  803. }
  804. inline void set_message_with_feedback(PGM_P const msg_P) {
  805. ui.set_status_P(msg_P);
  806. ui.quick_feedback();
  807. }
  808. void abort_fine_tune() {
  809. ui.return_to_status();
  810. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  811. set_message_with_feedback(PSTR(MSG_EDITING_STOPPED));
  812. }
  813. void unified_bed_leveling::fine_tune_mesh(const float &rx, const float &ry, const bool do_ubl_mesh_map) {
  814. if (!parser.seen('R')) // fine_tune_mesh() is special. If no repetition count flag is specified
  815. g29_repetition_cnt = 1; // do exactly one mesh location. Otherwise use what the parser decided.
  816. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  817. const float h_offset = parser.seenval('H') ? parser.value_linear_units() : 0;
  818. if (!WITHIN(h_offset, 0, 10)) {
  819. SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n");
  820. return;
  821. }
  822. #endif
  823. mesh_index_pair location;
  824. if (!position_is_reachable(rx, ry)) {
  825. SERIAL_ECHOLNPGM("(X,Y) outside printable radius.");
  826. return;
  827. }
  828. save_ubl_active_state_and_disable();
  829. LCD_MESSAGEPGM(MSG_UBL_FINE_TUNE_MESH);
  830. ui.capture(); // Take over control of the LCD encoder
  831. do_blocking_move_to(rx, ry, Z_CLEARANCE_BETWEEN_PROBES); // Move to the given XY with probe clearance
  832. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  833. do_blocking_move_to_z(h_offset); // Move Z to the given 'H' offset
  834. #endif
  835. uint16_t not_done[16];
  836. memset(not_done, 0xFF, sizeof(not_done));
  837. do {
  838. location = find_closest_mesh_point_of_type(SET_IN_BITMAP, rx, ry, USE_NOZZLE_AS_REFERENCE, not_done);
  839. if (location.x_index < 0) break; // Stop when there are no more reachable points
  840. bitmap_clear(not_done, location.x_index, location.y_index); // Mark this location as 'adjusted' so a new
  841. // location is used on the next loop
  842. const float rawx = mesh_index_to_xpos(location.x_index),
  843. rawy = mesh_index_to_ypos(location.y_index);
  844. if (!position_is_reachable(rawx, rawy)) break; // SHOULD NOT OCCUR because find_closest_mesh_point_of_type will only return reachable
  845. do_blocking_move_to(rawx, rawy, Z_CLEARANCE_BETWEEN_PROBES); // Move the nozzle to the edit point with probe clearance
  846. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  847. do_blocking_move_to_z(h_offset); // Move Z to the given 'H' offset before editing
  848. #endif
  849. KEEPALIVE_STATE(PAUSED_FOR_USER);
  850. if (do_ubl_mesh_map) display_map(g29_map_type); // Display the current point
  851. ui.refresh();
  852. float new_z = z_values[location.x_index][location.y_index];
  853. if (isnan(new_z)) new_z = 0; // Invalid points begin at 0
  854. new_z = FLOOR(new_z * 1000) * 0.001f; // Chop off digits after the 1000ths place
  855. lcd_mesh_edit_setup(new_z);
  856. do {
  857. new_z = lcd_mesh_edit();
  858. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  859. do_blocking_move_to_z(h_offset + new_z); // Move the nozzle as the point is edited
  860. #endif
  861. idle();
  862. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  863. } while (!ui.button_pressed());
  864. if (!lcd_map_control) ui.return_to_status(); // Just editing a single point? Return to status
  865. if (click_and_hold(abort_fine_tune)) goto FINE_TUNE_EXIT; // If the click is held down, abort editing
  866. z_values[location.x_index][location.y_index] = new_z; // Save the updated Z value
  867. #if ENABLED(EXTENSIBLE_UI)
  868. ExtUI::onMeshUpdate(location.x_index, location.y_index, new_z);
  869. #endif
  870. serial_delay(20); // No switch noise
  871. ui.refresh();
  872. } while (location.x_index >= 0 && --g29_repetition_cnt > 0);
  873. FINE_TUNE_EXIT:
  874. ui.release();
  875. KEEPALIVE_STATE(IN_HANDLER);
  876. if (do_ubl_mesh_map) display_map(g29_map_type);
  877. restore_ubl_active_state_and_leave();
  878. do_blocking_move_to(rx, ry, Z_CLEARANCE_BETWEEN_PROBES);
  879. LCD_MESSAGEPGM(MSG_UBL_DONE_EDITING_MESH);
  880. SERIAL_ECHOLNPGM("Done Editing Mesh");
  881. if (lcd_map_control)
  882. ui.goto_screen(_lcd_ubl_output_map_lcd);
  883. else
  884. ui.return_to_status();
  885. }
  886. #endif // HAS_LCD_MENU
  887. bool unified_bed_leveling::g29_parameter_parsing() {
  888. bool err_flag = false;
  889. #if HAS_LCD_MENU
  890. set_message_with_feedback(PSTR(MSG_UBL_DOING_G29));
  891. #endif
  892. g29_constant = 0;
  893. g29_repetition_cnt = 0;
  894. g29_x_flag = parser.seenval('X');
  895. g29_x_pos = g29_x_flag ? parser.value_float() : current_position[X_AXIS];
  896. g29_y_flag = parser.seenval('Y');
  897. g29_y_pos = g29_y_flag ? parser.value_float() : current_position[Y_AXIS];
  898. if (parser.seen('R')) {
  899. g29_repetition_cnt = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS;
  900. NOMORE(g29_repetition_cnt, GRID_MAX_POINTS);
  901. if (g29_repetition_cnt < 1) {
  902. SERIAL_ECHOLNPGM("?(R)epetition count invalid (1+).\n");
  903. return UBL_ERR;
  904. }
  905. }
  906. g29_verbose_level = parser.seen('V') ? parser.value_int() : 0;
  907. if (!WITHIN(g29_verbose_level, 0, 4)) {
  908. SERIAL_ECHOLNPGM("?(V)erbose level is implausible (0-4).\n");
  909. err_flag = true;
  910. }
  911. if (parser.seen('P')) {
  912. const int pv = parser.value_int();
  913. #if !HAS_BED_PROBE
  914. if (pv == 1) {
  915. SERIAL_ECHOLNPGM("G29 P1 requires a probe.\n");
  916. err_flag = true;
  917. }
  918. else
  919. #endif
  920. {
  921. g29_phase_value = pv;
  922. if (!WITHIN(g29_phase_value, 0, 6)) {
  923. SERIAL_ECHOLNPGM("?(P)hase value invalid (0-6).\n");
  924. err_flag = true;
  925. }
  926. }
  927. }
  928. if (parser.seen('J')) {
  929. #if HAS_BED_PROBE
  930. g29_grid_size = parser.has_value() ? parser.value_int() : 0;
  931. if (g29_grid_size && !WITHIN(g29_grid_size, 2, 9)) {
  932. SERIAL_ECHOLNPGM("?Invalid grid size (J) specified (2-9).\n");
  933. err_flag = true;
  934. }
  935. #else
  936. SERIAL_ECHOLNPGM("G29 J action requires a probe.\n");
  937. err_flag = true;
  938. #endif
  939. }
  940. if (g29_x_flag != g29_y_flag) {
  941. SERIAL_ECHOLNPGM("Both X & Y locations must be specified.\n");
  942. err_flag = true;
  943. }
  944. // If X or Y are not valid, use center of the bed values
  945. if (!WITHIN(g29_x_pos, X_MIN_BED, X_MAX_BED)) g29_x_pos = X_CENTER;
  946. if (!WITHIN(g29_y_pos, Y_MIN_BED, Y_MAX_BED)) g29_y_pos = Y_CENTER;
  947. if (err_flag) return UBL_ERR;
  948. /**
  949. * Activate or deactivate UBL
  950. * Note: UBL's G29 restores the state set here when done.
  951. * Leveling is being enabled here with old data, possibly
  952. * none. Error handling should disable for safety...
  953. */
  954. if (parser.seen('A')) {
  955. if (parser.seen('D')) {
  956. SERIAL_ECHOLNPGM("?Can't activate and deactivate at the same time.\n");
  957. return UBL_ERR;
  958. }
  959. set_bed_leveling_enabled(true);
  960. report_state();
  961. }
  962. else if (parser.seen('D')) {
  963. set_bed_leveling_enabled(false);
  964. report_state();
  965. }
  966. // Set global 'C' flag and its value
  967. if ((g29_c_flag = parser.seen('C')))
  968. g29_constant = parser.value_float();
  969. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  970. if (parser.seenval('F')) {
  971. const float fh = parser.value_float();
  972. if (!WITHIN(fh, 0, 100)) {
  973. SERIAL_ECHOLNPGM("?(F)ade height for Bed Level Correction not plausible.\n");
  974. return UBL_ERR;
  975. }
  976. set_z_fade_height(fh);
  977. }
  978. #endif
  979. g29_map_type = parser.intval('T');
  980. if (!WITHIN(g29_map_type, 0, 2)) {
  981. SERIAL_ECHOLNPGM("Invalid map type.\n");
  982. return UBL_ERR;
  983. }
  984. return UBL_OK;
  985. }
  986. static uint8_t ubl_state_at_invocation = 0;
  987. #if ENABLED(UBL_DEVEL_DEBUGGING)
  988. static uint8_t ubl_state_recursion_chk = 0;
  989. #endif
  990. void unified_bed_leveling::save_ubl_active_state_and_disable() {
  991. #if ENABLED(UBL_DEVEL_DEBUGGING)
  992. ubl_state_recursion_chk++;
  993. if (ubl_state_recursion_chk != 1) {
  994. SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row.");
  995. #if HAS_LCD_MENU
  996. set_message_with_feedback(PSTR(MSG_UBL_SAVE_ERROR));
  997. #endif
  998. return;
  999. }
  1000. #endif
  1001. ubl_state_at_invocation = planner.leveling_active;
  1002. set_bed_leveling_enabled(false);
  1003. }
  1004. void unified_bed_leveling::restore_ubl_active_state_and_leave() {
  1005. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1006. if (--ubl_state_recursion_chk) {
  1007. SERIAL_ECHOLNPGM("restore_ubl_active_state_and_leave() called too many times.");
  1008. #if HAS_LCD_MENU
  1009. set_message_with_feedback(PSTR(MSG_UBL_RESTORE_ERROR));
  1010. #endif
  1011. return;
  1012. }
  1013. #endif
  1014. set_bed_leveling_enabled(ubl_state_at_invocation);
  1015. }
  1016. mesh_index_pair unified_bed_leveling::find_furthest_invalid_mesh_point() {
  1017. bool found_a_NAN = false, found_a_real = false;
  1018. mesh_index_pair out_mesh;
  1019. out_mesh.x_index = out_mesh.y_index = -1;
  1020. out_mesh.distance = -99999.99f;
  1021. for (int8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1022. for (int8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
  1023. if (isnan(z_values[i][j])) { // Check to see if this location holds an invalid mesh point
  1024. const float mx = mesh_index_to_xpos(i),
  1025. my = mesh_index_to_ypos(j);
  1026. if (!position_is_reachable_by_probe(mx, my)) // make sure the probe can get to the mesh point
  1027. continue;
  1028. found_a_NAN = true;
  1029. int8_t closest_x = -1, closest_y = -1;
  1030. float d1, d2 = 99999.9f;
  1031. for (int8_t k = 0; k < GRID_MAX_POINTS_X; k++) {
  1032. for (int8_t l = 0; l < GRID_MAX_POINTS_Y; l++) {
  1033. if (!isnan(z_values[k][l])) {
  1034. found_a_real = true;
  1035. // Add in a random weighting factor that scrambles the probing of the
  1036. // last half of the mesh (when every unprobed mesh point is one index
  1037. // from a probed location).
  1038. d1 = HYPOT(i - k, j - l) + (1.0f / ((millis() % 47) + 13));
  1039. if (d1 < d2) { // found a closer distance from invalid mesh point at (i,j) to defined mesh point at (k,l)
  1040. d2 = d1; // found a closer location with
  1041. closest_x = i; // an assigned mesh point value
  1042. closest_y = j;
  1043. }
  1044. }
  1045. }
  1046. }
  1047. //
  1048. // At this point d2 should have the closest defined mesh point to invalid mesh point (i,j)
  1049. //
  1050. if (found_a_real && (closest_x >= 0) && (d2 > out_mesh.distance)) {
  1051. out_mesh.distance = d2; // found an invalid location with a greater distance
  1052. out_mesh.x_index = closest_x; // to a defined mesh point
  1053. out_mesh.y_index = closest_y;
  1054. }
  1055. }
  1056. } // for j
  1057. } // for i
  1058. if (!found_a_real && found_a_NAN) { // if the mesh is totally unpopulated, start the probing
  1059. out_mesh.x_index = GRID_MAX_POINTS_X / 2;
  1060. out_mesh.y_index = GRID_MAX_POINTS_Y / 2;
  1061. out_mesh.distance = 1;
  1062. }
  1063. return out_mesh;
  1064. }
  1065. mesh_index_pair unified_bed_leveling::find_closest_mesh_point_of_type(const MeshPointType type, const float &rx, const float &ry, const bool probe_as_reference, uint16_t bits[16]) {
  1066. mesh_index_pair out_mesh;
  1067. out_mesh.x_index = out_mesh.y_index = -1;
  1068. out_mesh.distance = -99999.9f;
  1069. // Get our reference position. Either the nozzle or probe location.
  1070. const float px = rx + (probe_as_reference == USE_PROBE_AS_REFERENCE ? X_PROBE_OFFSET_FROM_EXTRUDER : 0),
  1071. py = ry + (probe_as_reference == USE_PROBE_AS_REFERENCE ? Y_PROBE_OFFSET_FROM_EXTRUDER : 0);
  1072. float best_so_far = 99999.99f;
  1073. for (int8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1074. for (int8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
  1075. if ( (type == INVALID && isnan(z_values[i][j])) // Check to see if this location holds the right thing
  1076. || (type == REAL && !isnan(z_values[i][j]))
  1077. || (type == SET_IN_BITMAP && is_bitmap_set(bits, i, j))
  1078. ) {
  1079. // We only get here if we found a Mesh Point of the specified type
  1080. const float mx = mesh_index_to_xpos(i),
  1081. my = mesh_index_to_ypos(j);
  1082. // If using the probe as the reference there are some unreachable locations.
  1083. // Also for round beds, there are grid points outside the bed the nozzle can't reach.
  1084. // Prune them from the list and ignore them till the next Phase (manual nozzle probing).
  1085. if (probe_as_reference ? !position_is_reachable_by_probe(mx, my) : !position_is_reachable(mx, my))
  1086. continue;
  1087. // Reachable. Check if it's the best_so_far location to the nozzle.
  1088. float distance = HYPOT(px - mx, py - my);
  1089. // factor in the distance from the current location for the normal case
  1090. // so the nozzle isn't running all over the bed.
  1091. distance += HYPOT(current_position[X_AXIS] - mx, current_position[Y_AXIS] - my) * 0.1f;
  1092. if (distance < best_so_far) {
  1093. best_so_far = distance; // We found a closer location with
  1094. out_mesh.x_index = i; // the specified type of mesh value.
  1095. out_mesh.y_index = j;
  1096. out_mesh.distance = best_so_far;
  1097. }
  1098. }
  1099. } // for j
  1100. } // for i
  1101. return out_mesh;
  1102. }
  1103. /**
  1104. * 'Smart Fill': Scan from the outward edges of the mesh towards the center.
  1105. * If an invalid location is found, use the next two points (if valid) to
  1106. * calculate a 'reasonable' value for the unprobed mesh point.
  1107. */
  1108. bool unified_bed_leveling::smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  1109. const int8_t x1 = x + xdir, x2 = x1 + xdir,
  1110. y1 = y + ydir, y2 = y1 + ydir;
  1111. // A NAN next to a pair of real values?
  1112. if (isnan(z_values[x][y]) && !isnan(z_values[x1][y1]) && !isnan(z_values[x2][y2])) {
  1113. if (z_values[x1][y1] < z_values[x2][y2]) // Angled downward?
  1114. z_values[x][y] = z_values[x1][y1]; // Use nearest (maybe a little too high.)
  1115. else
  1116. z_values[x][y] = 2.0f * z_values[x1][y1] - z_values[x2][y2]; // Angled upward...
  1117. #if ENABLED(EXTENSIBLE_UI)
  1118. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  1119. #endif
  1120. return true;
  1121. }
  1122. return false;
  1123. }
  1124. typedef struct { uint8_t sx, ex, sy, ey; bool yfirst; } smart_fill_info;
  1125. void unified_bed_leveling::smart_fill_mesh() {
  1126. static const smart_fill_info
  1127. info0 PROGMEM = { 0, GRID_MAX_POINTS_X, 0, GRID_MAX_POINTS_Y - 2, false }, // Bottom of the mesh looking up
  1128. info1 PROGMEM = { 0, GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y - 1, 0, false }, // Top of the mesh looking down
  1129. info2 PROGMEM = { 0, GRID_MAX_POINTS_X - 2, 0, GRID_MAX_POINTS_Y, true }, // Left side of the mesh looking right
  1130. info3 PROGMEM = { GRID_MAX_POINTS_X - 1, 0, 0, GRID_MAX_POINTS_Y, true }; // Right side of the mesh looking left
  1131. static const smart_fill_info * const info[] PROGMEM = { &info0, &info1, &info2, &info3 };
  1132. for (uint8_t i = 0; i < COUNT(info); ++i) {
  1133. const smart_fill_info *f = (smart_fill_info*)pgm_read_ptr(&info[i]);
  1134. const int8_t sx = pgm_read_byte(&f->sx), sy = pgm_read_byte(&f->sy),
  1135. ex = pgm_read_byte(&f->ex), ey = pgm_read_byte(&f->ey);
  1136. if (pgm_read_byte(&f->yfirst)) {
  1137. const int8_t dir = ex > sx ? 1 : -1;
  1138. for (uint8_t y = sy; y != ey; ++y)
  1139. for (uint8_t x = sx; x != ex; x += dir)
  1140. if (smart_fill_one(x, y, dir, 0)) break;
  1141. }
  1142. else {
  1143. const int8_t dir = ey > sy ? 1 : -1;
  1144. for (uint8_t x = sx; x != ex; ++x)
  1145. for (uint8_t y = sy; y != ey; y += dir)
  1146. if (smart_fill_one(x, y, 0, dir)) break;
  1147. }
  1148. }
  1149. }
  1150. #if HAS_BED_PROBE
  1151. #include "../../../libs/vector_3.h"
  1152. void unified_bed_leveling::tilt_mesh_based_on_probed_grid(const bool do_3_pt_leveling) {
  1153. constexpr int16_t x_min = MAX(MIN_PROBE_X, MESH_MIN_X),
  1154. x_max = MIN(MAX_PROBE_X, MESH_MAX_X),
  1155. y_min = MAX(MIN_PROBE_Y, MESH_MIN_Y),
  1156. y_max = MIN(MAX_PROBE_Y, MESH_MAX_Y);
  1157. bool abort_flag = false;
  1158. float measured_z;
  1159. const float dx = float(x_max - x_min) / (g29_grid_size - 1),
  1160. dy = float(y_max - y_min) / (g29_grid_size - 1);
  1161. struct linear_fit_data lsf_results;
  1162. //float z1, z2, z3; // Needed for algorithm validation down below.
  1163. incremental_LSF_reset(&lsf_results);
  1164. if (do_3_pt_leveling) {
  1165. measured_z = probe_pt(PROBE_PT_1_X, PROBE_PT_1_Y, PROBE_PT_RAISE, g29_verbose_level);
  1166. if (isnan(measured_z))
  1167. abort_flag = true;
  1168. else {
  1169. measured_z -= get_z_correction(PROBE_PT_1_X, PROBE_PT_1_Y);
  1170. //z1 = measured_z;
  1171. if (g29_verbose_level > 3) {
  1172. serial_spaces(16);
  1173. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1174. }
  1175. incremental_LSF(&lsf_results, PROBE_PT_1_X, PROBE_PT_1_Y, measured_z);
  1176. }
  1177. if (!abort_flag) {
  1178. measured_z = probe_pt(PROBE_PT_2_X, PROBE_PT_2_Y, PROBE_PT_RAISE, g29_verbose_level);
  1179. //z2 = measured_z;
  1180. if (isnan(measured_z))
  1181. abort_flag = true;
  1182. else {
  1183. measured_z -= get_z_correction(PROBE_PT_2_X, PROBE_PT_2_Y);
  1184. if (g29_verbose_level > 3) {
  1185. serial_spaces(16);
  1186. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1187. }
  1188. incremental_LSF(&lsf_results, PROBE_PT_2_X, PROBE_PT_2_Y, measured_z);
  1189. }
  1190. }
  1191. if (!abort_flag) {
  1192. measured_z = probe_pt(PROBE_PT_3_X, PROBE_PT_3_Y, PROBE_PT_STOW, g29_verbose_level);
  1193. //z3 = measured_z;
  1194. if (isnan(measured_z))
  1195. abort_flag = true;
  1196. else {
  1197. measured_z -= get_z_correction(PROBE_PT_3_X, PROBE_PT_3_Y);
  1198. if (g29_verbose_level > 3) {
  1199. serial_spaces(16);
  1200. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1201. }
  1202. incremental_LSF(&lsf_results, PROBE_PT_3_X, PROBE_PT_3_Y, measured_z);
  1203. }
  1204. }
  1205. STOW_PROBE();
  1206. #ifdef Z_AFTER_PROBING
  1207. move_z_after_probing();
  1208. #endif
  1209. if (abort_flag) {
  1210. SERIAL_ECHOLNPGM("?Error probing point. Aborting operation.");
  1211. return;
  1212. }
  1213. }
  1214. else { // !do_3_pt_leveling
  1215. bool zig_zag = false;
  1216. for (uint8_t ix = 0; ix < g29_grid_size; ix++) {
  1217. const float rx = float(x_min) + ix * dx;
  1218. for (int8_t iy = 0; iy < g29_grid_size; iy++) {
  1219. const float ry = float(y_min) + dy * (zig_zag ? g29_grid_size - 1 - iy : iy);
  1220. if (!abort_flag) {
  1221. measured_z = probe_pt(rx, ry, parser.seen('E') ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level); // TODO: Needs error handling
  1222. abort_flag = isnan(measured_z);
  1223. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1224. if (DEBUGGING(LEVELING)) {
  1225. SERIAL_CHAR('(');
  1226. SERIAL_ECHO_F(rx, 7);
  1227. SERIAL_CHAR(',');
  1228. SERIAL_ECHO_F(ry, 7);
  1229. SERIAL_ECHOPGM(") logical: ");
  1230. SERIAL_CHAR('(');
  1231. SERIAL_ECHO_F(LOGICAL_X_POSITION(rx), 7);
  1232. SERIAL_CHAR(',');
  1233. SERIAL_ECHO_F(LOGICAL_Y_POSITION(ry), 7);
  1234. SERIAL_ECHOPAIR_F(") measured: ", measured_z, 7);
  1235. SERIAL_ECHOPAIR_F(" correction: ", get_z_correction(rx, ry), 7);
  1236. }
  1237. #endif
  1238. measured_z -= get_z_correction(rx, ry) /* + zprobe_zoffset */ ;
  1239. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1240. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR_F(" final >>>---> ", measured_z, 7);
  1241. #endif
  1242. if (g29_verbose_level > 3) {
  1243. serial_spaces(16);
  1244. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1245. }
  1246. incremental_LSF(&lsf_results, rx, ry, measured_z);
  1247. }
  1248. }
  1249. zig_zag ^= true;
  1250. }
  1251. }
  1252. STOW_PROBE();
  1253. #ifdef Z_AFTER_PROBING
  1254. move_z_after_probing();
  1255. #endif
  1256. if (abort_flag || finish_incremental_LSF(&lsf_results)) {
  1257. SERIAL_ECHOPGM("Could not complete LSF!");
  1258. return;
  1259. }
  1260. vector_3 normal = vector_3(lsf_results.A, lsf_results.B, 1).get_normal();
  1261. if (g29_verbose_level > 2) {
  1262. SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1263. SERIAL_CHAR(',');
  1264. SERIAL_ECHO_F(normal.y, 7);
  1265. SERIAL_CHAR(',');
  1266. SERIAL_ECHO_F(normal.z, 7);
  1267. SERIAL_ECHOLNPGM("]");
  1268. }
  1269. matrix_3x3 rotation = matrix_3x3::create_look_at(vector_3(lsf_results.A, lsf_results.B, 1));
  1270. for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1271. for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
  1272. float x_tmp = mesh_index_to_xpos(i),
  1273. y_tmp = mesh_index_to_ypos(j),
  1274. z_tmp = z_values[i][j];
  1275. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1276. if (DEBUGGING(LEVELING)) {
  1277. SERIAL_ECHOPAIR_F("before rotation = [", x_tmp, 7);
  1278. SERIAL_CHAR(',');
  1279. SERIAL_ECHO_F(y_tmp, 7);
  1280. SERIAL_CHAR(',');
  1281. SERIAL_ECHO_F(z_tmp, 7);
  1282. SERIAL_ECHOPGM("] ---> ");
  1283. serial_delay(20);
  1284. }
  1285. #endif
  1286. apply_rotation_xyz(rotation, x_tmp, y_tmp, z_tmp);
  1287. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1288. if (DEBUGGING(LEVELING)) {
  1289. SERIAL_ECHOPAIR_F("after rotation = [", x_tmp, 7);
  1290. SERIAL_CHAR(',');
  1291. SERIAL_ECHO_F(y_tmp, 7);
  1292. SERIAL_CHAR(',');
  1293. SERIAL_ECHO_F(z_tmp, 7);
  1294. SERIAL_ECHOLNPGM("]");
  1295. serial_delay(55);
  1296. }
  1297. #endif
  1298. z_values[i][j] = z_tmp - lsf_results.D;
  1299. #if ENABLED(EXTENSIBLE_UI)
  1300. ExtUI::onMeshUpdate(i, j, z_values[i][j]);
  1301. #endif
  1302. }
  1303. }
  1304. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1305. if (DEBUGGING(LEVELING)) {
  1306. rotation.debug(PSTR("rotation matrix:\n"));
  1307. SERIAL_ECHOPAIR_F("LSF Results A=", lsf_results.A, 7);
  1308. SERIAL_ECHOPAIR_F(" B=", lsf_results.B, 7);
  1309. SERIAL_ECHOLNPAIR_F(" D=", lsf_results.D, 7);
  1310. serial_delay(55);
  1311. SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1312. SERIAL_CHAR(',');
  1313. SERIAL_ECHO_F(normal.y, 7);
  1314. SERIAL_CHAR(',');
  1315. SERIAL_ECHO_F(normal.z, 7);
  1316. SERIAL_ECHOLNPGM("]");
  1317. SERIAL_EOL();
  1318. /**
  1319. * The following code can be used to check the validity of the mesh tilting algorithm.
  1320. * When a 3-Point Mesh Tilt is done, the same algorithm is used as the grid based tilting.
  1321. * The only difference is just 3 points are used in the calculations. That fact guarantees
  1322. * each probed point should have an exact match when a get_z_correction() for that location
  1323. * is calculated. The Z error between the probed point locations and the get_z_correction()
  1324. * numbers for those locations should be 0.
  1325. */
  1326. #if 0
  1327. float t, t1, d;
  1328. t = normal.x * (PROBE_PT_1_X) + normal.y * (PROBE_PT_1_Y);
  1329. d = t + normal.z * z1;
  1330. SERIAL_ECHOPAIR_F("D from 1st point: ", d, 6);
  1331. SERIAL_ECHOLNPAIR_F(" Z error: ", normal.z*z1-get_z_correction(PROBE_PT_1_X, PROBE_PT_1_Y), 6);
  1332. t = normal.x * (PROBE_PT_2_X) + normal.y * (PROBE_PT_2_Y);
  1333. d = t + normal.z * z2;
  1334. SERIAL_EOL();
  1335. SERIAL_ECHOPAIR_F("D from 2nd point: ", d, 6);
  1336. SERIAL_ECHOLNPAIR_F(" Z error: ", normal.z*z2-get_z_correction(PROBE_PT_2_X, PROBE_PT_2_Y), 6);
  1337. t = normal.x * (PROBE_PT_3_X) + normal.y * (PROBE_PT_3_Y);
  1338. d = t + normal.z * z3;
  1339. SERIAL_ECHOPAIR_F("D from 3rd point: ", d, 6);
  1340. SERIAL_ECHOLNPAIR_F(" Z error: ", normal.z*z3-get_z_correction(PROBE_PT_3_X, PROBE_PT_3_Y), 6);
  1341. t = normal.x * (Z_SAFE_HOMING_X_POINT) + normal.y * (Z_SAFE_HOMING_Y_POINT);
  1342. d = t + normal.z * 0;
  1343. SERIAL_ECHOLNPAIR_F("D from home location with Z=0 : ", d, 6);
  1344. t = normal.x * (Z_SAFE_HOMING_X_POINT) + normal.y * (Z_SAFE_HOMING_Y_POINT);
  1345. d = t + get_z_correction(Z_SAFE_HOMING_X_POINT, Z_SAFE_HOMING_Y_POINT); // normal.z * 0;
  1346. SERIAL_ECHOPAIR_F("D from home location using mesh value for Z: ", d, 6);
  1347. SERIAL_ECHOPAIR(" Z error: (", Z_SAFE_HOMING_X_POINT);
  1348. SERIAL_ECHOPAIR(",", Z_SAFE_HOMING_Y_POINT);
  1349. SERIAL_ECHOLNPAIR_F(") = ", get_z_correction(Z_SAFE_HOMING_X_POINT, Z_SAFE_HOMING_Y_POINT), 6);
  1350. #endif
  1351. } // DEBUGGING(LEVELING)
  1352. #endif
  1353. }
  1354. #endif // HAS_BED_PROBE
  1355. #if ENABLED(UBL_G29_P31)
  1356. void unified_bed_leveling::smart_fill_wlsf(const float &weight_factor) {
  1357. // For each undefined mesh point, compute a distance-weighted least squares fit
  1358. // from all the originally populated mesh points, weighted toward the point
  1359. // being extrapolated so that nearby points will have greater influence on
  1360. // the point being extrapolated. Then extrapolate the mesh point from WLSF.
  1361. static_assert(GRID_MAX_POINTS_Y <= 16, "GRID_MAX_POINTS_Y too big");
  1362. uint16_t bitmap[GRID_MAX_POINTS_X] = { 0 };
  1363. struct linear_fit_data lsf_results;
  1364. SERIAL_ECHOPGM("Extrapolating mesh...");
  1365. const float weight_scaled = weight_factor * MAX(MESH_X_DIST, MESH_Y_DIST);
  1366. for (uint8_t jx = 0; jx < GRID_MAX_POINTS_X; jx++)
  1367. for (uint8_t jy = 0; jy < GRID_MAX_POINTS_Y; jy++)
  1368. if (!isnan(z_values[jx][jy]))
  1369. SBI(bitmap[jx], jy);
  1370. for (uint8_t ix = 0; ix < GRID_MAX_POINTS_X; ix++) {
  1371. const float px = mesh_index_to_xpos(ix);
  1372. for (uint8_t iy = 0; iy < GRID_MAX_POINTS_Y; iy++) {
  1373. const float py = mesh_index_to_ypos(iy);
  1374. if (isnan(z_values[ix][iy])) {
  1375. // undefined mesh point at (px,py), compute weighted LSF from original valid mesh points.
  1376. incremental_LSF_reset(&lsf_results);
  1377. for (uint8_t jx = 0; jx < GRID_MAX_POINTS_X; jx++) {
  1378. const float rx = mesh_index_to_xpos(jx);
  1379. for (uint8_t jy = 0; jy < GRID_MAX_POINTS_Y; jy++) {
  1380. if (TEST(bitmap[jx], jy)) {
  1381. const float ry = mesh_index_to_ypos(jy),
  1382. rz = z_values[jx][jy],
  1383. w = 1 + weight_scaled / HYPOT((rx - px), (ry - py));
  1384. incremental_WLSF(&lsf_results, rx, ry, rz, w);
  1385. }
  1386. }
  1387. }
  1388. if (finish_incremental_LSF(&lsf_results)) {
  1389. SERIAL_ECHOLNPGM("Insufficient data");
  1390. return;
  1391. }
  1392. const float ez = -lsf_results.D - lsf_results.A * px - lsf_results.B * py;
  1393. z_values[ix][iy] = ez;
  1394. #if ENABLED(EXTENSIBLE_UI)
  1395. ExtUI::onMeshUpdate(ix, iy, z_values[ix][iy]);
  1396. #endif
  1397. idle(); // housekeeping
  1398. }
  1399. }
  1400. }
  1401. SERIAL_ECHOLNPGM("done");
  1402. }
  1403. #endif // UBL_G29_P31
  1404. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1405. /**
  1406. * Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  1407. * good to have the extra information. Soon... we prune this to just a few items
  1408. */
  1409. void unified_bed_leveling::g29_what_command() {
  1410. report_state();
  1411. if (storage_slot == -1)
  1412. SERIAL_ECHOPGM("No Mesh Loaded.");
  1413. else
  1414. SERIAL_ECHOPAIR("Mesh ", storage_slot, " Loaded.");
  1415. SERIAL_EOL();
  1416. serial_delay(50);
  1417. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1418. SERIAL_ECHOLNPAIR_F("planner.z_fade_height : ", planner.z_fade_height, 4);
  1419. #endif
  1420. adjust_mesh_to_mean(g29_c_flag, g29_constant);
  1421. #if HAS_BED_PROBE
  1422. SERIAL_ECHOLNPAIR_F("zprobe_zoffset: ", zprobe_zoffset, 7);
  1423. #endif
  1424. SERIAL_ECHOLNPAIR("MESH_MIN_X " STRINGIFY(MESH_MIN_X) "=", MESH_MIN_X); serial_delay(50);
  1425. SERIAL_ECHOLNPAIR("MESH_MIN_Y " STRINGIFY(MESH_MIN_Y) "=", MESH_MIN_Y); serial_delay(50);
  1426. SERIAL_ECHOLNPAIR("MESH_MAX_X " STRINGIFY(MESH_MAX_X) "=", MESH_MAX_X); serial_delay(50);
  1427. SERIAL_ECHOLNPAIR("MESH_MAX_Y " STRINGIFY(MESH_MAX_Y) "=", MESH_MAX_Y); serial_delay(50);
  1428. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_X ", GRID_MAX_POINTS_X); serial_delay(50);
  1429. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y); serial_delay(50);
  1430. SERIAL_ECHOLNPAIR("MESH_X_DIST ", MESH_X_DIST);
  1431. SERIAL_ECHOLNPAIR("MESH_Y_DIST ", MESH_Y_DIST); serial_delay(50);
  1432. SERIAL_ECHOPGM("X-Axis Mesh Points at: ");
  1433. for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1434. SERIAL_ECHO_F(LOGICAL_X_POSITION(mesh_index_to_xpos(i)), 3);
  1435. SERIAL_ECHOPGM(" ");
  1436. serial_delay(25);
  1437. }
  1438. SERIAL_EOL();
  1439. SERIAL_ECHOPGM("Y-Axis Mesh Points at: ");
  1440. for (uint8_t i = 0; i < GRID_MAX_POINTS_Y; i++) {
  1441. SERIAL_ECHO_F(LOGICAL_Y_POSITION(mesh_index_to_ypos(i)), 3);
  1442. SERIAL_ECHOPGM(" ");
  1443. serial_delay(25);
  1444. }
  1445. SERIAL_EOL();
  1446. #if HAS_KILL
  1447. SERIAL_ECHOLNPAIR("Kill pin on :", int(KILL_PIN), " state:", READ(KILL_PIN));
  1448. #endif
  1449. SERIAL_EOL();
  1450. serial_delay(50);
  1451. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1452. SERIAL_ECHOLNPAIR("ubl_state_at_invocation :", ubl_state_at_invocation, "\nubl_state_recursion_chk :", ubl_state_recursion_chk);
  1453. serial_delay(50);
  1454. SERIAL_ECHOLNPAIR("Meshes go from ", hex_address((void*)settings.meshes_start_index()), " to ", hex_address((void*)settings.meshes_end_index()));
  1455. serial_delay(50);
  1456. SERIAL_ECHOLNPAIR("sizeof(ubl) : ", (int)sizeof(ubl)); SERIAL_EOL();
  1457. SERIAL_ECHOLNPAIR("z_value[][] size: ", (int)sizeof(z_values)); SERIAL_EOL();
  1458. serial_delay(25);
  1459. SERIAL_ECHOLNPAIR("EEPROM free for UBL: ", hex_address((void*)(settings.meshes_end_index() - settings.meshes_start_index())));
  1460. serial_delay(50);
  1461. SERIAL_ECHOLNPAIR("EEPROM can hold ", settings.calc_num_meshes(), " meshes.\n");
  1462. serial_delay(25);
  1463. #endif // UBL_DEVEL_DEBUGGING
  1464. if (!sanity_check()) {
  1465. echo_name();
  1466. SERIAL_ECHOLNPGM(" sanity checks passed.");
  1467. }
  1468. }
  1469. /**
  1470. * When we are fully debugged, the EEPROM dump command will get deleted also. But
  1471. * right now, it is good to have the extra information. Soon... we prune this.
  1472. */
  1473. void unified_bed_leveling::g29_eeprom_dump() {
  1474. uint8_t cccc;
  1475. SERIAL_ECHO_MSG("EEPROM Dump:");
  1476. persistentStore.access_start();
  1477. for (uint16_t i = 0; i < persistentStore.capacity(); i += 16) {
  1478. if (!(i & 0x3)) idle();
  1479. print_hex_word(i);
  1480. SERIAL_ECHOPGM(": ");
  1481. for (uint16_t j = 0; j < 16; j++) {
  1482. persistentStore.read_data(i + j, &cccc, sizeof(uint8_t));
  1483. print_hex_byte(cccc);
  1484. SERIAL_CHAR(' ');
  1485. }
  1486. SERIAL_EOL();
  1487. }
  1488. SERIAL_EOL();
  1489. persistentStore.access_finish();
  1490. }
  1491. /**
  1492. * When we are fully debugged, this may go away. But there are some valid
  1493. * use cases for the users. So we can wait and see what to do with it.
  1494. */
  1495. void unified_bed_leveling::g29_compare_current_mesh_to_stored_mesh() {
  1496. const int16_t a = settings.calc_num_meshes();
  1497. if (!a) {
  1498. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  1499. return;
  1500. }
  1501. if (!parser.has_value() || !WITHIN(g29_storage_slot, 0, a - 1)) {
  1502. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  1503. return;
  1504. }
  1505. g29_storage_slot = parser.value_int();
  1506. float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  1507. settings.load_mesh(g29_storage_slot, &tmp_z_values);
  1508. SERIAL_ECHOLNPAIR("Subtracting mesh in slot ", g29_storage_slot, " from current mesh.");
  1509. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  1510. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++) {
  1511. z_values[x][y] -= tmp_z_values[x][y];
  1512. #if ENABLED(EXTENSIBLE_UI)
  1513. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  1514. #endif
  1515. }
  1516. }
  1517. #endif // UBL_DEVEL_DEBUGGING
  1518. #endif // AUTO_BED_LEVELING_UBL