My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ubl_G29.cpp 71KB

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