My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ubl_G29.cpp 75KB

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