My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ubl_G29.cpp 74KB

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