My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ubl_G29.cpp 73KB

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