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

ubl_G29.cpp 73KB

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