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

ubl_G29.cpp 72KB

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