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 70KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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 "planner.h"
  31. #include "ultralcd.h"
  32. #include <math.h>
  33. void lcd_babystep_z();
  34. void lcd_return_to_status();
  35. bool lcd_clicked();
  36. void lcd_implementation_clear();
  37. void lcd_mesh_edit_setup(float initial);
  38. void tilt_mesh_based_on_probed_grid(const bool);
  39. float lcd_mesh_edit();
  40. void lcd_z_offset_edit_setup(float);
  41. float lcd_z_offset_edit();
  42. extern float meshedit_done;
  43. extern long babysteps_done;
  44. extern float code_value_float();
  45. extern uint8_t code_value_byte();
  46. extern bool code_value_bool();
  47. extern bool code_has_value();
  48. extern float probe_pt(float x, float y, bool, int);
  49. extern bool set_probe_deployed(bool);
  50. bool ProbeStay = true;
  51. constexpr float ubl_3_point_1_X = UBL_PROBE_PT_1_X,
  52. ubl_3_point_1_Y = UBL_PROBE_PT_1_Y,
  53. ubl_3_point_2_X = UBL_PROBE_PT_2_X,
  54. ubl_3_point_2_Y = UBL_PROBE_PT_2_Y,
  55. ubl_3_point_3_X = UBL_PROBE_PT_3_X,
  56. ubl_3_point_3_Y = UBL_PROBE_PT_3_Y;
  57. #define SIZE_OF_LITTLE_RAISE 0
  58. #define BIG_RAISE_NOT_NEEDED 0
  59. extern void lcd_quick_feedback();
  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. * N No Home G29 normally insists that a G28 has been performed. You can over rule this with an
  130. * N option. In general, you should not do this. This can only be done safely with
  131. * commands that do not move the nozzle.
  132. *
  133. * The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will
  134. * start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with
  135. * each additional Phase that processes it.
  136. *
  137. * P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the
  138. * 3D Printer to the same state it was in before the Unified Bed Leveling Compensation
  139. * was turned on. Setting the entire Mesh to Zero is a special case that allows
  140. * a subsequent G or T leveling operation for backward compatibility.
  141. *
  142. * P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using
  143. * the Z-Probe. Depending upon the values of DELTA_PROBEABLE_RADIUS and
  144. * DELTA_PRINTABLE_RADIUS some area of the bed will not have Mesh Data automatically
  145. * generated. This will be handled in Phase 2. If the Phase 1 command is given the
  146. * C (Continue) parameter it does not invalidate the Mesh prior to automatically
  147. * probing needed locations. This allows you to invalidate portions of the Mesh but still
  148. * use the automatic probing capabilities of the Unified Bed Leveling System. An X and Y
  149. * parameter can be given to prioritize where the command should be trying to measure points.
  150. * If the X and Y parameters are not specified the current probe position is used. Phase 1
  151. * allows you to specify the M (Map) parameter so you can watch the generation of the Mesh.
  152. * Phase 1 also watches for the LCD Panel's Encoder Switch being held in a depressed state.
  153. * It will suspend generation of the Mesh if it sees the user request that. (This check is
  154. * only done between probe points. You will need to press and hold the switch until the
  155. * Phase 1 command can detect it.)
  156. *
  157. * P2 Phase 2 Probe areas of the Mesh that can't be automatically handled. Phase 2 respects an H
  158. * parameter to control the height between Mesh points. The default height for movement
  159. * between Mesh points is 5mm. A smaller number can be used to make this part of the
  160. * calibration less time consuming. You will be running the nozzle down until it just barely
  161. * touches the glass. You should have the nozzle clean with no plastic obstructing your view.
  162. * Use caution and move slowly. It is possible to damage your printer if you are careless.
  163. * Note that this command will use the configuration #define SIZE_OF_LITTLE_RAISE if the
  164. * nozzle is moving a distance of less than BIG_RAISE_NOT_NEEDED.
  165. *
  166. * The H parameter can be set negative if your Mesh dips in a large area. You can press
  167. * and hold the LCD Panel's encoder wheel to terminate the current Phase 2 command. You
  168. * can then re-issue the G29 P 2 command with an H parameter that is more suitable for the
  169. * area you are manually probing. Note that the command tries to start you in a corner
  170. * of the bed where movement will be predictable. You can force the location to be used in
  171. * the distance calculations by using the X and Y parameters. You may find it is helpful to
  172. * print out a Mesh Map (G29 O) to understand where the mesh is invalidated and where
  173. * the nozzle will need to move in order to complete the command. The C parameter is
  174. * available on the Phase 2 command also and indicates the search for points to measure should
  175. * be done based on the current location of the nozzle.
  176. *
  177. * A B parameter is also available for this command and described up above. It places the
  178. * manual probe subsystem into Business Card mode where the thickness of a business care is
  179. * measured and then used to accurately set the nozzle height in all manual probing for the
  180. * duration of the command. (S for Shim mode would be a better parameter name, but S is needed
  181. * for Save or Store of the Mesh to EEPROM) A Business card can be used, but you will have
  182. * better results if you use a flexible Shim that does not compress very much. That makes it
  183. * easier for you to get the nozzle to press with similar amounts of force against the shim so you
  184. * can get accurate measurements. As you are starting to touch the nozzle against the shim try
  185. * to get it to grasp the shim with the same force as when you measured the thickness of the
  186. * shim at the start of the command.
  187. *
  188. * Phase 2 allows the O (Map) parameter to be specified. This helps the user see the progression
  189. * of the Mesh being built.
  190. *
  191. * P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. The C parameter is
  192. * used to specify the 'constant' value to fill all invalid areas of the Mesh. If no C parameter
  193. * is specified, a value of 0.0 is assumed. The R parameter can be given to specify the number
  194. * of points to set. If the R parameter is specified the current nozzle position is used to
  195. * find the closest points to alter unless the X and Y parameter are used to specify the fill
  196. * location.
  197. *
  198. * P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assume the existance of
  199. * an LCD Panel. It is possible to fine tune the mesh without the use of an LCD Panel.
  200. * (More work and details on doing this later!)
  201. * The System will search for the closest Mesh Point to the nozzle. It will move the
  202. * nozzle to this location. The user can use the LCD Panel to carefully adjust the nozzle
  203. * so it is just barely touching the bed. When the user clicks the control, the System
  204. * will lock in that height for that point in the Mesh Compensation System.
  205. *
  206. * Phase 4 has several additional parameters that the user may find helpful. Phase 4
  207. * can be started at a specific location by specifying an X and Y parameter. Phase 4
  208. * can be requested to continue the adjustment of Mesh Points by using the R(epeat)
  209. * parameter. If the Repetition count is not specified, it is assumed the user wishes
  210. * to adjust the entire matrix. The nozzle is moved to the Mesh Point being edited.
  211. * The command can be terminated early (or after the area of interest has been edited) by
  212. * pressing and holding the encoder wheel until the system recognizes the exit request.
  213. * Phase 4's general form is G29 P4 [R # of points] [X position] [Y position]
  214. *
  215. * Phase 4 is intended to be used with the G26 Mesh Validation Command. Using the
  216. * information left on the printer's bed from the G26 command it is very straight forward
  217. * and easy to fine tune the Mesh. One concept that is important to remember and that
  218. * will make using the Phase 4 command easy to use is this: You are editing the Mesh Points.
  219. * If you have too little clearance and not much plastic was extruded in an area, you want to
  220. * LOWER the Mesh Point at the location. If you did not get good adheasion, you want to
  221. * RAISE the Mesh Point at that location.
  222. *
  223. *
  224. * P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and
  225. * work with the Mesh if it is Mean Adjusted. You can specify a C parameter to
  226. * Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically
  227. * execute a G29 P6 C <mean height>.
  228. *
  229. * P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified
  230. * with the C parameter. Being able to adjust the height of a Mesh is useful tool. It
  231. * can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally,
  232. * you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring
  233. * 0.000 at the Z Home location.
  234. *
  235. * Q Test * Load specified Test Pattern to assist in checking correct operation of system. This
  236. * command is not anticipated to be of much value to the typical user. It is intended
  237. * for developers to help them verify correct operation of the Unified Bed Leveling System.
  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. It will also store the current state of
  244. * the Unified Bed Leveling system in the EEPROM.
  245. *
  246. * S -1 Store Store the current Mesh as a print out that is suitable to be feed back into
  247. * the system at a later date. The text generated can be saved and later sent by PronterFace or
  248. * Repetier Host to reconstruct the current mesh on another machine.
  249. *
  250. * T 3-Point Perform a 3 Point Bed Leveling on the current Mesh
  251. *
  252. * U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds.
  253. * Only used for G29 P1 O U It will speed up the probing of the edge of the bed. This
  254. * is useful when the entire bed does not need to be probed because it will be adjusted.
  255. *
  256. * W What? Display valuable data the Unified Bed Leveling System knows.
  257. *
  258. * X # * * X Location for this line of commands
  259. *
  260. * Y # * * Y Location for this line of commands
  261. *
  262. * Z Zero * Probes to set the Z Height of the nozzle. The entire Mesh can be raised or lowered
  263. * by just doing a G29 Z
  264. *
  265. * Z # Zero * The entire Mesh can be raised or lowered to conform with the specified difference.
  266. * zprobe_zoffset is added to the calculation.
  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 = -1, 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, measured_z, card_thickness = 0.0, ubl_constant = 0.0;
  301. #if ENABLED(ULTRA_LCD)
  302. extern void lcd_setstatus(const char* message, const bool persist);
  303. extern void lcd_setstatuspgm(const char* message, const uint8_t level);
  304. #endif
  305. void gcode_G29() {
  306. SERIAL_PROTOCOLLNPAIR("ubl.eeprom_start=", ubl.eeprom_start);
  307. if (ubl.eeprom_start < 0) {
  308. SERIAL_PROTOCOLLNPGM("?You need to enable your EEPROM and initialize it");
  309. SERIAL_PROTOCOLLNPGM("with M502, M500, M501 in that order.\n");
  310. return;
  311. }
  312. if (!code_seen('N') && axis_unhomed_error(true, true, true)) // Don't allow auto-leveling without homing first
  313. gcode_G28();
  314. if (g29_parameter_parsing()) return; // abort if parsing the simple parameters causes a problem,
  315. // Invalidate Mesh Points. This command is a little bit asymetrical because
  316. // it directly specifies the repetition count and does not use the 'R' parameter.
  317. if (code_seen('I')) {
  318. int cnt = 0;
  319. repetition_cnt = code_has_value() ? code_value_int() : 1;
  320. while (repetition_cnt--) {
  321. if (cnt>20) {
  322. cnt = 0;
  323. idle();
  324. }
  325. const mesh_index_pair location = find_closest_mesh_point_of_type(REAL, x_pos, y_pos, 0, NULL, false); // The '0' says we want to use the nozzle's position
  326. if (location.x_index < 0) {
  327. SERIAL_PROTOCOLLNPGM("Entire Mesh invalidated.\n");
  328. break; // No more invalid Mesh Points to populate
  329. }
  330. ubl.z_values[location.x_index][location.y_index] = NAN;
  331. }
  332. SERIAL_PROTOCOLLNPGM("Locations invalidated.\n");
  333. }
  334. if (code_seen('Q')) {
  335. const int test_pattern = code_has_value() ? code_value_int() : -1;
  336. if (!WITHIN(test_pattern, 0, 2)) {
  337. SERIAL_PROTOCOLLNPGM("Invalid test_pattern value. (0-2)\n");
  338. return;
  339. }
  340. SERIAL_PROTOCOLLNPGM("Loading test_pattern values.\n");
  341. switch (test_pattern) {
  342. case 0:
  343. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) { // Create a bowl shape - similar to
  344. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++) { // a poorly calibrated Delta.
  345. const float p1 = 0.5 * (GRID_MAX_POINTS_X) - x,
  346. p2 = 0.5 * (GRID_MAX_POINTS_Y) - y;
  347. ubl.z_values[x][y] += 2.0 * HYPOT(p1, p2);
  348. }
  349. }
  350. break;
  351. case 1:
  352. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++) { // Create a diagonal line several Mesh cells thick that is raised
  353. ubl.z_values[x][x] += 9.999;
  354. ubl.z_values[x][x + (x < GRID_MAX_POINTS_Y - 1) ? 1 : -1] += 9.999; // We want the altered line several mesh points thick
  355. }
  356. break;
  357. case 2:
  358. // Allow the user to specify the height because 10mm is a little extreme in some cases.
  359. for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in
  360. for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) // the center of the bed
  361. ubl.z_values[x][y] += code_seen('C') ? ubl_constant : 9.99;
  362. break;
  363. }
  364. }
  365. if (code_seen('J')) {
  366. if (grid_size<2 || grid_size>5) {
  367. SERIAL_PROTOCOLLNPGM("ERROR - grid size must be between 2 and 5");
  368. return;
  369. }
  370. tilt_mesh_based_on_probed_grid(code_seen('O') || code_seen('M'));
  371. }
  372. if (code_seen('P')) {
  373. phase_value = code_value_int();
  374. if (!WITHIN(phase_value, 0, 7)) {
  375. SERIAL_PROTOCOLLNPGM("Invalid Phase value. (0-4)\n");
  376. return;
  377. }
  378. switch (phase_value) {
  379. case 0:
  380. //
  381. // Zero Mesh Data
  382. //
  383. ubl.reset();
  384. SERIAL_PROTOCOLLNPGM("Mesh zeroed.\n");
  385. break;
  386. case 1:
  387. //
  388. // Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
  389. //
  390. if (!code_seen('C')) {
  391. ubl.invalidate();
  392. SERIAL_PROTOCOLLNPGM("Mesh invalidated. Probing mesh.\n");
  393. }
  394. if (g29_verbose_level > 1) {
  395. SERIAL_PROTOCOLPAIR("Probing Mesh Points Closest to (", x_pos);
  396. SERIAL_PROTOCOLCHAR(',');
  397. SERIAL_PROTOCOL(y_pos);
  398. SERIAL_PROTOCOLLNPGM(")\n");
  399. }
  400. probe_entire_mesh(x_pos + X_PROBE_OFFSET_FROM_EXTRUDER, y_pos + Y_PROBE_OFFSET_FROM_EXTRUDER,
  401. code_seen('O') || code_seen('M'), code_seen('E'), code_seen('U'));
  402. break;
  403. case 2: {
  404. //
  405. // Manually Probe Mesh in areas that can't be reached by the probe
  406. //
  407. SERIAL_PROTOCOLLNPGM("Manually probing unreachable mesh locations.\n");
  408. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  409. if (!x_flag && !y_flag) { // use a good default location for the path
  410. // The flipped > and < operators on these two comparisons is
  411. // intentional. It should cause the probed points to follow a
  412. // nice path on Cartesian printers. It may make sense to
  413. // have Delta printers default to the center of the bed.
  414. // For now, until that is decided, it can be forced with the X
  415. // and Y parameters.
  416. x_pos = X_PROBE_OFFSET_FROM_EXTRUDER > 0 ? X_MAX_POS : X_MIN_POS;
  417. y_pos = Y_PROBE_OFFSET_FROM_EXTRUDER < 0 ? Y_MAX_POS : Y_MIN_POS;
  418. }
  419. if (code_seen('C')) {
  420. x_pos = current_position[X_AXIS];
  421. y_pos = current_position[Y_AXIS];
  422. }
  423. const float height = code_seen('H') && code_has_value() ? code_value_float() : Z_CLEARANCE_BETWEEN_PROBES;
  424. if (code_seen('B')) {
  425. card_thickness = code_has_value() ? code_value_float() : measure_business_card_thickness(height);
  426. if (fabs(card_thickness) > 1.5) {
  427. SERIAL_PROTOCOLLNPGM("?Error in Business Card measurement.\n");
  428. return;
  429. }
  430. }
  431. manually_probe_remaining_mesh(x_pos, y_pos, height, card_thickness, code_seen('O') || code_seen('M'));
  432. } break;
  433. case 3: {
  434. //
  435. // Populate invalid Mesh areas with a constant
  436. //
  437. const float height = code_seen('C') ? ubl_constant : 0.0;
  438. // If no repetition is specified, do the whole Mesh
  439. if (!repeat_flag) repetition_cnt = 9999;
  440. while (repetition_cnt--) {
  441. const mesh_index_pair location = find_closest_mesh_point_of_type(INVALID, x_pos, y_pos, 0, NULL, false); // The '0' says we want to use the nozzle's position
  442. if (location.x_index < 0) break; // No more invalid Mesh Points to populate
  443. ubl.z_values[location.x_index][location.y_index] = height;
  444. }
  445. } break;
  446. case 4:
  447. //
  448. // Fine Tune (i.e., Edit) the Mesh
  449. //
  450. fine_tune_mesh(x_pos, y_pos, code_seen('O') || code_seen('M'));
  451. break;
  452. case 5:
  453. find_mean_mesh_height();
  454. break;
  455. case 6:
  456. shift_mesh_height();
  457. break;
  458. case 10:
  459. // [DEBUG] Pay no attention to this stuff. It can be removed soon.
  460. SERIAL_ECHO_START;
  461. SERIAL_ECHOLNPGM("Checking G29 has control of LCD Panel:");
  462. KEEPALIVE_STATE(PAUSED_FOR_USER);
  463. ubl.has_control_of_lcd_panel = true;
  464. while (!ubl_lcd_clicked()) {
  465. safe_delay(250);
  466. if (ubl.encoder_diff) {
  467. SERIAL_ECHOLN((int)ubl.encoder_diff);
  468. ubl.encoder_diff = 0;
  469. }
  470. }
  471. SERIAL_ECHOLNPGM("G29 giving back control of LCD Panel.");
  472. ubl.has_control_of_lcd_panel = false;
  473. KEEPALIVE_STATE(IN_HANDLER);
  474. break;
  475. case 11:
  476. // [DEBUG] wait_for_user code. Pay no attention to this stuff. It can be removed soon.
  477. SERIAL_ECHO_START;
  478. SERIAL_ECHOLNPGM("Checking G29 has control of LCD Panel:");
  479. KEEPALIVE_STATE(PAUSED_FOR_USER);
  480. wait_for_user = true;
  481. while (wait_for_user) {
  482. safe_delay(250);
  483. if (ubl.encoder_diff) {
  484. SERIAL_ECHOLN((int)ubl.encoder_diff);
  485. ubl.encoder_diff = 0;
  486. }
  487. }
  488. SERIAL_ECHOLNPGM("G29 giving back control of LCD Panel.");
  489. KEEPALIVE_STATE(IN_HANDLER);
  490. break;
  491. }
  492. }
  493. if (code_seen('T')) {
  494. const float lx1 = LOGICAL_X_POSITION(ubl_3_point_1_X),
  495. lx2 = LOGICAL_X_POSITION(ubl_3_point_2_X),
  496. lx3 = LOGICAL_X_POSITION(ubl_3_point_3_X),
  497. ly1 = LOGICAL_Y_POSITION(ubl_3_point_1_Y),
  498. ly2 = LOGICAL_Y_POSITION(ubl_3_point_2_Y),
  499. ly3 = LOGICAL_Y_POSITION(ubl_3_point_3_Y);
  500. float z1 = probe_pt(lx1, ly1, false /*Stow Flag*/, g29_verbose_level),
  501. z2 = probe_pt(lx2, ly2, false /*Stow Flag*/, g29_verbose_level),
  502. z3 = probe_pt(lx3, ly3, true /*Stow Flag*/, g29_verbose_level);
  503. // We need to adjust z1, z2, z3 by the Mesh Height at these points. Just because they are non-zero doesn't mean
  504. // the Mesh is tilted! (We need to compensate each probe point by what the Mesh says that location's height is)
  505. z1 -= ubl.get_z_correction(lx1, ly1);
  506. z2 -= ubl.get_z_correction(lx2, ly2);
  507. z3 -= ubl.get_z_correction(lx3, ly3);
  508. do_blocking_move_to_xy((X_MAX_POS - (X_MIN_POS)) / 2.0, (Y_MAX_POS - (Y_MIN_POS)) / 2.0);
  509. tilt_mesh_based_on_3pts(z1, z2, z3);
  510. }
  511. //
  512. // Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  513. // good to have the extra information. Soon... we prune this to just a few items
  514. //
  515. if (code_seen('W')) g29_what_command();
  516. //
  517. // When we are fully debugged, the EEPROM dump command will get deleted also. But
  518. // right now, it is good to have the extra information. Soon... we prune this.
  519. //
  520. if (code_seen('j')) g29_eeprom_dump(); // EEPROM Dump
  521. //
  522. // When we are fully debugged, this may go away. But there are some valid
  523. // use cases for the users. So we can wait and see what to do with it.
  524. //
  525. if (code_seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
  526. g29_compare_current_mesh_to_stored_mesh();
  527. //
  528. // Load a Mesh from the EEPROM
  529. //
  530. if (code_seen('L')) { // Load Current Mesh Data
  531. storage_slot = code_has_value() ? code_value_int() : ubl.state.eeprom_storage_slot;
  532. const int16_t j = (UBL_LAST_EEPROM_INDEX - ubl.eeprom_start) / sizeof(ubl.z_values);
  533. if (!WITHIN(storage_slot, 0, j - 1) || ubl.eeprom_start <= 0) {
  534. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available for use.\n");
  535. return;
  536. }
  537. ubl.load_mesh(storage_slot);
  538. ubl.state.eeprom_storage_slot = storage_slot;
  539. if (storage_slot != ubl.state.eeprom_storage_slot)
  540. ubl.store_state();
  541. SERIAL_PROTOCOLLNPGM("Done.\n");
  542. }
  543. //
  544. // Store a Mesh in the EEPROM
  545. //
  546. if (code_seen('S')) { // Store (or Save) Current Mesh Data
  547. storage_slot = code_has_value() ? code_value_int() : ubl.state.eeprom_storage_slot;
  548. if (storage_slot == -1) { // Special case, we are going to 'Export' the mesh to the
  549. SERIAL_ECHOLNPGM("G29 I 999"); // host in a form it can be reconstructed on a different machine
  550. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  551. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  552. if (!isnan(ubl.z_values[x][y])) {
  553. SERIAL_ECHOPAIR("M421 I ", x);
  554. SERIAL_ECHOPAIR(" J ", y);
  555. SERIAL_ECHOPGM(" Z ");
  556. SERIAL_ECHO_F(ubl.z_values[x][y], 6);
  557. SERIAL_EOL;
  558. }
  559. return;
  560. }
  561. const int16_t j = (UBL_LAST_EEPROM_INDEX - ubl.eeprom_start) / sizeof(ubl.z_values);
  562. if (!WITHIN(storage_slot, 0, j - 1) || ubl.eeprom_start <= 0) {
  563. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available for use.\n");
  564. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", j - 1);
  565. goto LEAVE;
  566. }
  567. ubl.store_mesh(storage_slot);
  568. ubl.state.eeprom_storage_slot = storage_slot;
  569. //
  570. // if (storage_slot != ubl.state.eeprom_storage_slot)
  571. ubl.store_state(); // Always save an updated copy of the UBL State info
  572. SERIAL_PROTOCOLLNPGM("Done.\n");
  573. }
  574. if (code_seen('O') || code_seen('M'))
  575. ubl.display_map(code_has_value() ? code_value_int() : 0);
  576. if (code_seen('Z')) {
  577. if (code_has_value())
  578. ubl.state.z_offset = code_value_float(); // do the simple case. Just lock in the specified value
  579. else {
  580. save_ubl_active_state_and_disable();
  581. //measured_z = probe_pt(x_pos + X_PROBE_OFFSET_FROM_EXTRUDER, y_pos + Y_PROBE_OFFSET_FROM_EXTRUDER, ProbeDeployAndStow, g29_verbose_level);
  582. ubl.has_control_of_lcd_panel = true; // Grab the LCD Hardware
  583. measured_z = 1.5;
  584. do_blocking_move_to_z(measured_z); // Get close to the bed, but leave some space so we don't damage anything
  585. // The user is not going to be locking in a new Z-Offset very often so
  586. // it won't be that painful to spin the Encoder Wheel for 1.5mm
  587. lcd_implementation_clear();
  588. lcd_z_offset_edit_setup(measured_z);
  589. KEEPALIVE_STATE(PAUSED_FOR_USER);
  590. do {
  591. measured_z = lcd_z_offset_edit();
  592. idle();
  593. do_blocking_move_to_z(measured_z);
  594. } while (!ubl_lcd_clicked());
  595. ubl.has_control_of_lcd_panel = true; // There is a race condition for the Encoder Wheel getting clicked.
  596. // It could get detected in lcd_mesh_edit (actually _lcd_mesh_fine_tune)
  597. // or here. So, until we are done looking for a long Encoder Wheel Press,
  598. // we need to take control of the panel
  599. KEEPALIVE_STATE(IN_HANDLER);
  600. lcd_return_to_status();
  601. const millis_t nxt = millis() + 1500UL;
  602. while (ubl_lcd_clicked()) { // debounce and watch for abort
  603. idle();
  604. if (ELAPSED(millis(), nxt)) {
  605. SERIAL_PROTOCOLLNPGM("\nZ-Offset Adjustment Stopped.");
  606. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  607. LCD_MESSAGEPGM("Z-Offset Stopped");
  608. restore_ubl_active_state_and_leave();
  609. goto LEAVE;
  610. }
  611. }
  612. ubl.has_control_of_lcd_panel = false;
  613. safe_delay(20); // We don't want any switch noise.
  614. ubl.state.z_offset = measured_z;
  615. lcd_implementation_clear();
  616. restore_ubl_active_state_and_leave();
  617. }
  618. }
  619. LEAVE:
  620. lcd_reset_alert_level();
  621. LCD_MESSAGEPGM("");
  622. lcd_quick_feedback();
  623. ubl.has_control_of_lcd_panel = false;
  624. }
  625. void find_mean_mesh_height() {
  626. uint8_t x, y;
  627. int n;
  628. float sum, sum_of_diff_squared, sigma, difference, mean;
  629. sum = sum_of_diff_squared = 0.0;
  630. n = 0;
  631. for (x = 0; x < GRID_MAX_POINTS_X; x++)
  632. for (y = 0; y < GRID_MAX_POINTS_Y; y++)
  633. if (!isnan(ubl.z_values[x][y])) {
  634. sum += ubl.z_values[x][y];
  635. n++;
  636. }
  637. mean = sum / n;
  638. //
  639. // Now do the sumation of the squares of difference from mean
  640. //
  641. for (x = 0; x < GRID_MAX_POINTS_X; x++)
  642. for (y = 0; y < GRID_MAX_POINTS_Y; y++)
  643. if (!isnan(ubl.z_values[x][y])) {
  644. difference = (ubl.z_values[x][y] - mean);
  645. sum_of_diff_squared += difference * difference;
  646. }
  647. SERIAL_ECHOLNPAIR("# of samples: ", n);
  648. SERIAL_ECHOPGM("Mean Mesh Height: ");
  649. SERIAL_ECHO_F(mean, 6);
  650. SERIAL_EOL;
  651. sigma = sqrt(sum_of_diff_squared / (n + 1));
  652. SERIAL_ECHOPGM("Standard Deviation: ");
  653. SERIAL_ECHO_F(sigma, 6);
  654. SERIAL_EOL;
  655. if (c_flag)
  656. for (x = 0; x < GRID_MAX_POINTS_X; x++)
  657. for (y = 0; y < GRID_MAX_POINTS_Y; y++)
  658. if (!isnan(ubl.z_values[x][y]))
  659. ubl.z_values[x][y] -= mean + ubl_constant;
  660. }
  661. void shift_mesh_height() {
  662. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  663. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  664. if (!isnan(ubl.z_values[x][y]))
  665. ubl.z_values[x][y] += ubl_constant;
  666. }
  667. /**
  668. * Probe all invalidated locations of the mesh that can be reached by the probe.
  669. * This attempts to fill in locations closest to the nozzle's start location first.
  670. */
  671. void probe_entire_mesh(const float &lx, const float &ly, const bool do_ubl_mesh_map, const bool stow_probe, bool do_furthest) {
  672. mesh_index_pair location;
  673. ubl.has_control_of_lcd_panel = true;
  674. save_ubl_active_state_and_disable(); // we don't do bed level correction because we want the raw data when we probe
  675. DEPLOY_PROBE();
  676. do {
  677. if (ubl_lcd_clicked()) {
  678. SERIAL_PROTOCOLLNPGM("\nMesh only partially populated.\n");
  679. lcd_quick_feedback();
  680. STOW_PROBE();
  681. while (ubl_lcd_clicked()) idle();
  682. ubl.has_control_of_lcd_panel = false;
  683. restore_ubl_active_state_and_leave();
  684. safe_delay(50); // Debounce the Encoder wheel
  685. return;
  686. }
  687. location = find_closest_mesh_point_of_type(INVALID, lx, ly, 1, NULL, do_furthest); // the '1' says we want the location to be relative to the probe
  688. if (location.x_index >= 0 && location.y_index >= 0) {
  689. const float rawx = ubl.mesh_index_to_xpos[location.x_index],
  690. rawy = ubl.mesh_index_to_ypos[location.y_index];
  691. // TODO: Change to use `position_is_reachable` (for SCARA-compatibility)
  692. if (!WITHIN(rawx, MIN_PROBE_X, MAX_PROBE_X) || !WITHIN(rawy, MIN_PROBE_Y, MAX_PROBE_Y)) {
  693. SERIAL_ERROR_START;
  694. SERIAL_ERRORLNPGM("Attempt to probe off the bed.");
  695. ubl.has_control_of_lcd_panel = false;
  696. goto LEAVE;
  697. }
  698. const float measured_z = probe_pt(LOGICAL_X_POSITION(rawx), LOGICAL_Y_POSITION(rawy), stow_probe, g29_verbose_level);
  699. ubl.z_values[location.x_index][location.y_index] = measured_z;
  700. }
  701. if (do_ubl_mesh_map) ubl.display_map(map_type);
  702. } while (location.x_index >= 0 && location.y_index >= 0);
  703. LEAVE:
  704. STOW_PROBE();
  705. restore_ubl_active_state_and_leave();
  706. do_blocking_move_to_xy(
  707. constrain(lx - (X_PROBE_OFFSET_FROM_EXTRUDER), X_MIN_POS, X_MAX_POS),
  708. constrain(ly - (Y_PROBE_OFFSET_FROM_EXTRUDER), Y_MIN_POS, Y_MAX_POS)
  709. );
  710. }
  711. vector_3 tilt_mesh_based_on_3pts(const float &z1, const float &z2, const float &z3) {
  712. float c, d, t;
  713. int i, j;
  714. vector_3 v1 = vector_3( (ubl_3_point_1_X - ubl_3_point_2_X),
  715. (ubl_3_point_1_Y - ubl_3_point_2_Y),
  716. (z1 - z2) ),
  717. v2 = vector_3( (ubl_3_point_3_X - ubl_3_point_2_X),
  718. (ubl_3_point_3_Y - ubl_3_point_2_Y),
  719. (z3 - z2) ),
  720. normal = vector_3::cross(v1, v2);
  721. // printf("[%f,%f,%f] ", normal.x, normal.y, normal.z);
  722. /**
  723. * This code does two things. This vector is normal to the tilted plane.
  724. * However, we don't know its direction. We need it to point up. So if
  725. * Z is negative, we need to invert the sign of all components of the vector
  726. * We also need Z to be unity because we are going to be treating this triangle
  727. * as the sin() and cos() of the bed's tilt
  728. */
  729. const float inv_z = 1.0 / normal.z;
  730. normal.x *= inv_z;
  731. normal.y *= inv_z;
  732. normal.z = 1.0;
  733. //
  734. // All of 3 of these points should give us the same d constant
  735. //
  736. t = normal.x * ubl_3_point_1_X + normal.y * ubl_3_point_1_Y;
  737. d = t + normal.z * z1;
  738. c = d - t;
  739. SERIAL_ECHOPGM("d from 1st point: ");
  740. SERIAL_ECHO_F(d, 6);
  741. SERIAL_ECHOPGM(" c: ");
  742. SERIAL_ECHO_F(c, 6);
  743. SERIAL_EOL;
  744. t = normal.x * ubl_3_point_2_X + normal.y * ubl_3_point_2_Y;
  745. d = t + normal.z * z2;
  746. c = d - t;
  747. SERIAL_ECHOPGM("d from 2nd point: ");
  748. SERIAL_ECHO_F(d, 6);
  749. SERIAL_ECHOPGM(" c: ");
  750. SERIAL_ECHO_F(c, 6);
  751. SERIAL_EOL;
  752. t = normal.x * ubl_3_point_3_X + normal.y * ubl_3_point_3_Y;
  753. d = t + normal.z * z3;
  754. c = d - t;
  755. SERIAL_ECHOPGM("d from 3rd point: ");
  756. SERIAL_ECHO_F(d, 6);
  757. SERIAL_ECHOPGM(" c: ");
  758. SERIAL_ECHO_F(c, 6);
  759. SERIAL_EOL;
  760. for (i = 0; i < GRID_MAX_POINTS_X; i++) {
  761. for (j = 0; j < GRID_MAX_POINTS_Y; j++) {
  762. c = -((normal.x * (UBL_MESH_MIN_X + i * (MESH_X_DIST)) + normal.y * (UBL_MESH_MIN_Y + j * (MESH_Y_DIST))) - d);
  763. ubl.z_values[i][j] += c;
  764. }
  765. }
  766. return normal;
  767. }
  768. float use_encoder_wheel_to_measure_point() {
  769. KEEPALIVE_STATE(PAUSED_FOR_USER);
  770. while (!ubl_lcd_clicked()) { // we need the loop to move the nozzle based on the encoder wheel here!
  771. idle();
  772. if (ubl.encoder_diff) {
  773. do_blocking_move_to_z(current_position[Z_AXIS] + 0.01 * float(ubl.encoder_diff));
  774. ubl.encoder_diff = 0;
  775. }
  776. }
  777. KEEPALIVE_STATE(IN_HANDLER);
  778. return current_position[Z_AXIS];
  779. }
  780. float measure_business_card_thickness(const float &in_height) {
  781. ubl.has_control_of_lcd_panel = true;
  782. save_ubl_active_state_and_disable(); // we don't do bed level correction because we want the raw data when we probe
  783. SERIAL_PROTOCOLLNPGM("Place Shim Under Nozzle and Perform Measurement.");
  784. do_blocking_move_to_z(in_height);
  785. do_blocking_move_to_xy((float(X_MAX_POS) - float(X_MIN_POS)) / 2.0, (float(Y_MAX_POS) - float(Y_MIN_POS)) / 2.0);
  786. //, min(planner.max_feedrate_mm_s[X_AXIS], planner.max_feedrate_mm_s[Y_AXIS])/2.0);
  787. const float z1 = use_encoder_wheel_to_measure_point();
  788. do_blocking_move_to_z(current_position[Z_AXIS] + SIZE_OF_LITTLE_RAISE);
  789. ubl.has_control_of_lcd_panel = false;
  790. SERIAL_PROTOCOLLNPGM("Remove Shim and Measure Bed Height.");
  791. const float z2 = use_encoder_wheel_to_measure_point();
  792. do_blocking_move_to_z(current_position[Z_AXIS] + SIZE_OF_LITTLE_RAISE);
  793. if (g29_verbose_level > 1) {
  794. SERIAL_PROTOCOLPGM("Business Card is: ");
  795. SERIAL_PROTOCOL_F(abs(z1 - z2), 6);
  796. SERIAL_PROTOCOLLNPGM("mm thick.");
  797. }
  798. restore_ubl_active_state_and_leave();
  799. return abs(z1 - z2);
  800. }
  801. 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) {
  802. ubl.has_control_of_lcd_panel = true;
  803. save_ubl_active_state_and_disable(); // we don't do bed level correction because we want the raw data when we probe
  804. do_blocking_move_to_z(z_clearance);
  805. do_blocking_move_to_xy(lx, ly);
  806. float last_x = -9999.99, last_y = -9999.99;
  807. mesh_index_pair location;
  808. do {
  809. location = find_closest_mesh_point_of_type(INVALID, lx, ly, 0, NULL, false); // The '0' says we want to use the nozzle's position
  810. // It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
  811. if (location.x_index < 0 && location.y_index < 0) continue;
  812. const float rawx = ubl.mesh_index_to_xpos[location.x_index],
  813. rawy = ubl.mesh_index_to_ypos[location.y_index];
  814. // TODO: Change to use `position_is_reachable` (for SCARA-compatibility)
  815. if (!WITHIN(rawx, X_MIN_POS, X_MAX_POS) || !WITHIN(rawy, Y_MIN_POS, Y_MAX_POS)) {
  816. SERIAL_ERROR_START;
  817. SERIAL_ERRORLNPGM("Attempt to probe off the bed.");
  818. ubl.has_control_of_lcd_panel = false;
  819. goto LEAVE;
  820. }
  821. const float xProbe = LOGICAL_X_POSITION(rawx),
  822. yProbe = LOGICAL_Y_POSITION(rawy),
  823. dx = xProbe - last_x,
  824. dy = yProbe - last_y;
  825. if (HYPOT(dx, dy) < BIG_RAISE_NOT_NEEDED)
  826. do_blocking_move_to_z(current_position[Z_AXIS] + SIZE_OF_LITTLE_RAISE);
  827. else
  828. do_blocking_move_to_z(z_clearance);
  829. do_blocking_move_to_xy(xProbe, yProbe);
  830. last_x = xProbe;
  831. last_y = yProbe;
  832. KEEPALIVE_STATE(PAUSED_FOR_USER);
  833. ubl.has_control_of_lcd_panel = true;
  834. if (do_ubl_mesh_map) ubl.display_map(map_type); // show user where we're probing
  835. while (!ubl_lcd_clicked()) { // we need the loop to move the nozzle based on the encoder wheel here!
  836. idle();
  837. if (ubl.encoder_diff) {
  838. do_blocking_move_to_z(current_position[Z_AXIS] + float(ubl.encoder_diff) / 100.0);
  839. ubl.encoder_diff = 0;
  840. }
  841. }
  842. const millis_t nxt = millis() + 1500L;
  843. while (ubl_lcd_clicked()) { // debounce and watch for abort
  844. idle();
  845. if (ELAPSED(millis(), nxt)) {
  846. SERIAL_PROTOCOLLNPGM("\nMesh only partially populated.");
  847. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  848. lcd_quick_feedback();
  849. while (ubl_lcd_clicked()) idle();
  850. ubl.has_control_of_lcd_panel = false;
  851. KEEPALIVE_STATE(IN_HANDLER);
  852. restore_ubl_active_state_and_leave();
  853. return;
  854. }
  855. }
  856. ubl.z_values[location.x_index][location.y_index] = current_position[Z_AXIS] - card_thickness;
  857. if (g29_verbose_level > 2) {
  858. SERIAL_PROTOCOLPGM("Mesh Point Measured at: ");
  859. SERIAL_PROTOCOL_F(ubl.z_values[location.x_index][location.y_index], 6);
  860. SERIAL_EOL;
  861. }
  862. } while (location.x_index >= 0 && location.y_index >= 0);
  863. if (do_ubl_mesh_map) ubl.display_map(map_type);
  864. LEAVE:
  865. restore_ubl_active_state_and_leave();
  866. KEEPALIVE_STATE(IN_HANDLER);
  867. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  868. do_blocking_move_to_xy(lx, ly);
  869. }
  870. bool g29_parameter_parsing() {
  871. bool err_flag = false;
  872. LCD_MESSAGEPGM("Doing G29 UBL!");
  873. lcd_quick_feedback();
  874. x_flag = code_seen('X') && code_has_value();
  875. x_pos = x_flag ? code_value_float() : current_position[X_AXIS];
  876. y_flag = code_seen('Y') && code_has_value();
  877. y_pos = y_flag ? code_value_float() : current_position[Y_AXIS];
  878. repetition_cnt = 0;
  879. repeat_flag = code_seen('R');
  880. if (repeat_flag) {
  881. repetition_cnt = code_has_value() ? code_value_int() : GRID_MAX_POINTS_X*GRID_MAX_POINTS_Y;
  882. if (repetition_cnt < 1) {
  883. SERIAL_PROTOCOLLNPGM("Invalid Repetition count.\n");
  884. return UBL_ERR;
  885. }
  886. }
  887. g29_verbose_level = code_seen('V') ? code_value_int() : 0;
  888. if (!WITHIN(g29_verbose_level, 0, 4)) {
  889. SERIAL_PROTOCOLLNPGM("Invalid Verbose Level specified. (0-4)\n");
  890. err_flag = true;
  891. }
  892. if (code_seen('G')) {
  893. grid_size = code_has_value() ? code_value_int() : 3;
  894. if (!WITHIN(grid_size, 2, 5)) {
  895. SERIAL_PROTOCOLLNPGM("Invalid grid probe points specified.\n");
  896. err_flag = true;
  897. }
  898. }
  899. if (x_flag != y_flag) {
  900. SERIAL_PROTOCOLLNPGM("Both X & Y locations must be specified.\n");
  901. err_flag = true;
  902. }
  903. if (!WITHIN(RAW_X_POSITION(x_pos), X_MIN_POS, X_MAX_POS)) {
  904. SERIAL_PROTOCOLLNPGM("Invalid X location specified.\n");
  905. err_flag = true;
  906. SERIAL_PROTOCOLPAIR("\nx_flag = ", x_flag); // These print blocks are only useful because sometimes the
  907. SERIAL_PROTOCOLPAIR("\nx_pos = ", x_pos ); // data corruption causes x_pos and y_pos to be crazy. This gets deleted soon.
  908. SERIAL_PROTOCOLPAIR("\ncurrent[] = ", current_position[X_AXIS]);
  909. SERIAL_PROTOCOLPAIR("\nX_MIN_POS = ", X_MIN_POS);
  910. SERIAL_PROTOCOLPAIR("\nX_MAX_POS = ", X_MAX_POS);
  911. SERIAL_PROTOCOLPAIR("\nRAW_X_POSITION() = ", RAW_X_POSITION(x_pos));
  912. SERIAL_PROTOCOLPAIR("\nwithin() = ", WITHIN(RAW_X_POSITION(x_pos), X_MIN_POS, X_MAX_POS));
  913. SERIAL_PROTOCOL("\n");
  914. }
  915. if (!WITHIN(RAW_Y_POSITION(y_pos), Y_MIN_POS, Y_MAX_POS)) {
  916. SERIAL_PROTOCOLLNPGM("Invalid Y location specified.\n");
  917. err_flag = true;
  918. SERIAL_PROTOCOLPAIR("\ny_flag = ", y_flag); // These print blocks are only useful because sometimes the
  919. SERIAL_PROTOCOLPAIR("\ny_pos = ", y_pos ); // data corruption causes x_pos and y_pos to be crazy. This gets deleted soon.
  920. SERIAL_PROTOCOLPAIR("\ncurrent[] = ", current_position[Y_AXIS]);
  921. SERIAL_PROTOCOLPAIR("\nY_MIN_POS = ", Y_MIN_POS);
  922. SERIAL_PROTOCOLPAIR("\nY_MAX_POS = ", Y_MAX_POS);
  923. SERIAL_PROTOCOLPAIR("\nRAW_Y_POSITION() = ", RAW_Y_POSITION(y_pos));
  924. SERIAL_PROTOCOLPAIR("\nwithin() = ", WITHIN(RAW_Y_POSITION(y_pos), Y_MIN_POS, Y_MAX_POS));
  925. SERIAL_PROTOCOL("\n");
  926. }
  927. if (err_flag) return UBL_ERR;
  928. if (code_seen('A')) { // Activate the Unified Bed Leveling System
  929. ubl.state.active = 1;
  930. SERIAL_PROTOCOLLNPGM("Unified Bed Leveling System activated.\n");
  931. ubl.store_state();
  932. }
  933. c_flag = code_seen('C') && code_has_value();
  934. ubl_constant = c_flag ? code_value_float() : 0.0;
  935. if (code_seen('D')) { // Disable the Unified Bed Leveling System
  936. ubl.state.active = 0;
  937. SERIAL_PROTOCOLLNPGM("Unified Bed Leveling System de-activated.\n");
  938. ubl.store_state();
  939. }
  940. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  941. if (code_seen('F') && code_has_value()) {
  942. const float fh = code_value_float();
  943. if (!WITHIN(fh, 0.0, 100.0)) {
  944. SERIAL_PROTOCOLLNPGM("?Bed Level Correction Fade Height Not Plausible.\n");
  945. return UBL_ERR;
  946. }
  947. ubl.state.g29_correction_fade_height = fh;
  948. ubl.state.g29_fade_height_multiplier = 1.0 / fh;
  949. }
  950. #endif
  951. map_type = code_seen('O') && code_has_value() ? code_value_int() : 0;
  952. if (!WITHIN(map_type, 0, 1)) {
  953. SERIAL_PROTOCOLLNPGM("Invalid map type.\n");
  954. return UBL_ERR;
  955. }
  956. if (code_seen('M')) { // Check if a map type was specified
  957. map_type = code_has_value() ? code_value_int() : 0;
  958. if (!WITHIN(map_type, 0, 1)) {
  959. SERIAL_PROTOCOLLNPGM("Invalid map type.\n");
  960. return UBL_ERR;
  961. }
  962. }
  963. return UBL_OK;
  964. }
  965. /**
  966. * This function goes away after G29 debug is complete. But for right now, it is a handy
  967. * routine to dump binary data structures.
  968. */
  969. /*
  970. void dump(char * const str, const float &f) {
  971. char *ptr;
  972. SERIAL_PROTOCOL(str);
  973. SERIAL_PROTOCOL_F(f, 8);
  974. SERIAL_PROTOCOLPGM(" ");
  975. ptr = (char*)&f;
  976. for (uint8_t i = 0; i < 4; i++)
  977. SERIAL_PROTOCOLPAIR(" ", hex_byte(*ptr++));
  978. SERIAL_PROTOCOLPAIR(" isnan()=", isnan(f));
  979. SERIAL_PROTOCOLPAIR(" isinf()=", isinf(f));
  980. if (f == -INFINITY)
  981. SERIAL_PROTOCOLPGM(" Minus Infinity detected.");
  982. SERIAL_EOL;
  983. }
  984. */
  985. static int ubl_state_at_invocation = 0,
  986. ubl_state_recursion_chk = 0;
  987. void save_ubl_active_state_and_disable() {
  988. ubl_state_recursion_chk++;
  989. if (ubl_state_recursion_chk != 1) {
  990. SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row.");
  991. LCD_MESSAGEPGM("save_UBL_active() error");
  992. lcd_quick_feedback();
  993. return;
  994. }
  995. ubl_state_at_invocation = ubl.state.active;
  996. ubl.state.active = 0;
  997. }
  998. void restore_ubl_active_state_and_leave() {
  999. if (--ubl_state_recursion_chk) {
  1000. SERIAL_ECHOLNPGM("restore_ubl_active_state_and_leave() called too many times.");
  1001. LCD_MESSAGEPGM("restore_UBL_active() error");
  1002. lcd_quick_feedback();
  1003. return;
  1004. }
  1005. ubl.state.active = ubl_state_at_invocation;
  1006. }
  1007. /**
  1008. * Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  1009. * good to have the extra information. Soon... we prune this to just a few items
  1010. */
  1011. void g29_what_command() {
  1012. const uint16_t k = E2END - ubl.eeprom_start;
  1013. SERIAL_PROTOCOLPGM("Unified Bed Leveling System Version " UBL_VERSION " ");
  1014. if (ubl.state.active)
  1015. SERIAL_PROTOCOLCHAR('A');
  1016. else
  1017. SERIAL_PROTOCOLPGM("Ina");
  1018. SERIAL_PROTOCOLLNPGM("ctive.\n");
  1019. safe_delay(50);
  1020. if (ubl.state.eeprom_storage_slot == -1)
  1021. SERIAL_PROTOCOLPGM("No Mesh Loaded.");
  1022. else {
  1023. SERIAL_PROTOCOLPAIR("Mesh ", ubl.state.eeprom_storage_slot);
  1024. SERIAL_PROTOCOLPGM(" Loaded.");
  1025. }
  1026. SERIAL_EOL;
  1027. safe_delay(50);
  1028. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1029. SERIAL_PROTOCOLLNPAIR("g29_correction_fade_height : ", ubl.state.g29_correction_fade_height);
  1030. #endif
  1031. SERIAL_PROTOCOLPGM("z_offset: ");
  1032. SERIAL_PROTOCOL_F(ubl.state.z_offset, 6);
  1033. SERIAL_EOL;
  1034. safe_delay(50);
  1035. SERIAL_PROTOCOLPGM("X-Axis Mesh Points at: ");
  1036. for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1037. SERIAL_PROTOCOL_F(LOGICAL_X_POSITION(ubl.mesh_index_to_xpos[i]), 1);
  1038. SERIAL_PROTOCOLPGM(" ");
  1039. safe_delay(50);
  1040. }
  1041. SERIAL_EOL;
  1042. SERIAL_PROTOCOLPGM("Y-Axis Mesh Points at: ");
  1043. for (uint8_t i = 0; i < GRID_MAX_POINTS_Y; i++) {
  1044. SERIAL_PROTOCOL_F(LOGICAL_Y_POSITION(ubl.mesh_index_to_ypos[i]), 1);
  1045. SERIAL_PROTOCOLPGM(" ");
  1046. safe_delay(50);
  1047. }
  1048. SERIAL_EOL;
  1049. #if HAS_KILL
  1050. SERIAL_PROTOCOLPAIR("Kill pin on :", KILL_PIN);
  1051. SERIAL_PROTOCOLLNPAIR(" state:", READ(KILL_PIN));
  1052. #endif
  1053. SERIAL_EOL;
  1054. safe_delay(50);
  1055. SERIAL_PROTOCOLLNPAIR("ubl_state_at_invocation :", ubl_state_at_invocation);
  1056. SERIAL_EOL;
  1057. SERIAL_PROTOCOLLNPAIR("ubl_state_recursion_chk :", ubl_state_recursion_chk);
  1058. SERIAL_EOL;
  1059. safe_delay(50);
  1060. SERIAL_PROTOCOLLNPAIR("Free EEPROM space starts at: 0x", hex_word(ubl.eeprom_start));
  1061. SERIAL_PROTOCOLLNPAIR("end of EEPROM : 0x", hex_word(E2END));
  1062. safe_delay(50);
  1063. SERIAL_PROTOCOLLNPAIR("sizeof(ubl) : ", (int)sizeof(ubl));
  1064. SERIAL_EOL;
  1065. SERIAL_PROTOCOLLNPAIR("z_value[][] size: ", (int)sizeof(ubl.z_values));
  1066. SERIAL_EOL;
  1067. safe_delay(50);
  1068. SERIAL_PROTOCOLLNPAIR("EEPROM free for UBL: 0x", hex_word(k));
  1069. safe_delay(50);
  1070. SERIAL_PROTOCOLPAIR("EEPROM can hold ", k / sizeof(ubl.z_values));
  1071. SERIAL_PROTOCOLLNPGM(" meshes.\n");
  1072. safe_delay(50);
  1073. SERIAL_PROTOCOLPAIR("sizeof(ubl.state) : ", (int)sizeof(ubl.state));
  1074. SERIAL_PROTOCOLPAIR("\nGRID_MAX_POINTS_X ", GRID_MAX_POINTS_X);
  1075. SERIAL_PROTOCOLPAIR("\nGRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y);
  1076. safe_delay(50);
  1077. SERIAL_PROTOCOLPAIR("\nUBL_MESH_MIN_X ", UBL_MESH_MIN_X);
  1078. SERIAL_PROTOCOLPAIR("\nUBL_MESH_MIN_Y ", UBL_MESH_MIN_Y);
  1079. safe_delay(50);
  1080. SERIAL_PROTOCOLPAIR("\nUBL_MESH_MAX_X ", UBL_MESH_MAX_X);
  1081. SERIAL_PROTOCOLPAIR("\nUBL_MESH_MAX_Y ", UBL_MESH_MAX_Y);
  1082. safe_delay(50);
  1083. SERIAL_PROTOCOLPGM("\nMESH_X_DIST ");
  1084. SERIAL_PROTOCOL_F(MESH_X_DIST, 6);
  1085. SERIAL_PROTOCOLPGM("\nMESH_Y_DIST ");
  1086. SERIAL_PROTOCOL_F(MESH_Y_DIST, 6);
  1087. SERIAL_EOL;
  1088. safe_delay(50);
  1089. if (!ubl.sanity_check())
  1090. SERIAL_PROTOCOLLNPGM("Unified Bed Leveling sanity checks passed.");
  1091. }
  1092. /**
  1093. * When we are fully debugged, the EEPROM dump command will get deleted also. But
  1094. * right now, it is good to have the extra information. Soon... we prune this.
  1095. */
  1096. void g29_eeprom_dump() {
  1097. unsigned char cccc;
  1098. uint16_t kkkk;
  1099. SERIAL_ECHO_START;
  1100. SERIAL_ECHOLNPGM("EEPROM Dump:");
  1101. for (uint16_t i = 0; i < E2END + 1; i += 16) {
  1102. if (!(i & 0x3)) idle();
  1103. print_hex_word(i);
  1104. SERIAL_ECHOPGM(": ");
  1105. for (uint16_t j = 0; j < 16; j++) {
  1106. kkkk = i + j;
  1107. eeprom_read_block(&cccc, (void *)kkkk, 1);
  1108. print_hex_byte(cccc);
  1109. SERIAL_ECHO(' ');
  1110. }
  1111. SERIAL_EOL;
  1112. }
  1113. SERIAL_EOL;
  1114. }
  1115. /**
  1116. * When we are fully debugged, this may go away. But there are some valid
  1117. * use cases for the users. So we can wait and see what to do with it.
  1118. */
  1119. void g29_compare_current_mesh_to_stored_mesh() {
  1120. float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  1121. if (!code_has_value()) {
  1122. SERIAL_PROTOCOLLNPGM("?Mesh # required.\n");
  1123. return;
  1124. }
  1125. storage_slot = code_value_int();
  1126. int16_t j = (UBL_LAST_EEPROM_INDEX - ubl.eeprom_start) / sizeof(tmp_z_values);
  1127. if (!WITHIN(storage_slot, 0, j - 1) || ubl.eeprom_start <= 0) {
  1128. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available for use.\n");
  1129. return;
  1130. }
  1131. j = UBL_LAST_EEPROM_INDEX - (storage_slot + 1) * sizeof(tmp_z_values);
  1132. eeprom_read_block((void *)&tmp_z_values, (void *)j, sizeof(tmp_z_values));
  1133. SERIAL_ECHOPAIR("Subtracting Mesh ", storage_slot);
  1134. SERIAL_PROTOCOLLNPAIR(" loaded from EEPROM address 0x", hex_word(j)); // Soon, we can remove the extra clutter of printing
  1135. // the address in the EEPROM where the Mesh is stored.
  1136. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  1137. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  1138. ubl.z_values[x][y] -= tmp_z_values[x][y];
  1139. }
  1140. 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], bool far_flag) {
  1141. float distance, closest = far_flag ? -99999.99 : 99999.99;
  1142. mesh_index_pair return_val;
  1143. return_val.x_index = return_val.y_index = -1;
  1144. const float current_x = current_position[X_AXIS],
  1145. current_y = current_position[Y_AXIS];
  1146. // Get our reference position. Either the nozzle or probe location.
  1147. const float px = lx - (probe_as_reference ? X_PROBE_OFFSET_FROM_EXTRUDER : 0),
  1148. py = ly - (probe_as_reference ? Y_PROBE_OFFSET_FROM_EXTRUDER : 0);
  1149. for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
  1150. for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
  1151. if ( (type == INVALID && isnan(ubl.z_values[i][j])) // Check to see if this location holds the right thing
  1152. || (type == REAL && !isnan(ubl.z_values[i][j]))
  1153. || (type == SET_IN_BITMAP && is_bit_set(bits, i, j))
  1154. ) {
  1155. // We only get here if we found a Mesh Point of the specified type
  1156. const float rawx = ubl.mesh_index_to_xpos[i], // Check if we can probe this mesh location
  1157. rawy = ubl.mesh_index_to_ypos[j];
  1158. // If using the probe as the reference there are some unreachable locations.
  1159. // Prune them from the list and ignore them till the next Phase (manual nozzle probing).
  1160. if (probe_as_reference &&
  1161. (!WITHIN(rawx, MIN_PROBE_X, MAX_PROBE_X) || !WITHIN(rawy, MIN_PROBE_Y, MAX_PROBE_Y))
  1162. ) continue;
  1163. // Unreachable. Check if it's the closest location to the nozzle.
  1164. // Add in a weighting factor that considers the current location of the nozzle.
  1165. const float mx = LOGICAL_X_POSITION(rawx), // Check if we can probe this mesh location
  1166. my = LOGICAL_Y_POSITION(rawy);
  1167. distance = HYPOT(px - mx, py - my) + HYPOT(current_x - mx, current_y - my) * 0.1;
  1168. if (far_flag) { // If doing the far_flag action, we want to be as far as possible
  1169. for (uint8_t k = 0; k < GRID_MAX_POINTS_X; k++) { // from the starting point and from any other probed points. We
  1170. for (uint8_t l = 0; l < GRID_MAX_POINTS_Y; l++) { // want the next point spread out and filling in any blank spaces
  1171. if (!isnan(ubl.z_values[k][l])) { // in the mesh. So we add in some of the distance to every probed
  1172. distance += sq(i - k) * (MESH_X_DIST) * .05 // point we can find.
  1173. + sq(j - l) * (MESH_Y_DIST) * .05;
  1174. }
  1175. }
  1176. }
  1177. }
  1178. if (far_flag == (distance > closest) && distance != closest) { // if far_flag, look for farthest point
  1179. closest = distance; // We found a closer/farther location with
  1180. return_val.x_index = i; // the specified type of mesh value.
  1181. return_val.y_index = j;
  1182. return_val.distance = closest;
  1183. }
  1184. }
  1185. } // for j
  1186. } // for i
  1187. return return_val;
  1188. }
  1189. void fine_tune_mesh(const float &lx, const float &ly, const bool do_ubl_mesh_map) {
  1190. if (!code_seen('R')) // fine_tune_mesh() is special. If no repetion count flag is specified
  1191. repetition_cnt = 1; // we know to do exactly one mesh location. Otherwise we use what the parser decided.
  1192. mesh_index_pair location;
  1193. uint16_t not_done[16];
  1194. int32_t round_off;
  1195. save_ubl_active_state_and_disable();
  1196. memset(not_done, 0xFF, sizeof(not_done));
  1197. LCD_MESSAGEPGM("Fine Tuning Mesh");
  1198. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  1199. do_blocking_move_to_xy(lx, ly);
  1200. do {
  1201. location = find_closest_mesh_point_of_type(SET_IN_BITMAP, lx, ly, 0, not_done, false); // The '0' says we want to use the nozzle's position
  1202. // It doesn't matter if the probe can not reach this
  1203. // location. This is a manual edit of the Mesh Point.
  1204. if (location.x_index < 0 && location.y_index < 0) continue; // abort if we can't find any more points.
  1205. bit_clear(not_done, location.x_index, location.y_index); // Mark this location as 'adjusted' so we will find a
  1206. // different location the next time through the loop
  1207. const float rawx = ubl.mesh_index_to_xpos[location.x_index],
  1208. rawy = ubl.mesh_index_to_ypos[location.y_index];
  1209. // TODO: Change to use `position_is_reachable` (for SCARA-compatibility)
  1210. if (!WITHIN(rawx, X_MIN_POS, X_MAX_POS) || !WITHIN(rawy, Y_MIN_POS, Y_MAX_POS)) { // In theory, we don't need this check.
  1211. SERIAL_ERROR_START;
  1212. SERIAL_ERRORLNPGM("Attempt to edit off the bed."); // This really can't happen, but do the check for now
  1213. ubl.has_control_of_lcd_panel = false;
  1214. goto FINE_TUNE_EXIT;
  1215. }
  1216. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE); // Move the nozzle to where we are going to edit
  1217. do_blocking_move_to_xy(LOGICAL_X_POSITION(rawx), LOGICAL_Y_POSITION(rawy));
  1218. float new_z = ubl.z_values[location.x_index][location.y_index];
  1219. round_off = (int32_t)(new_z * 1000.0); // we chop off the last digits just to be clean. We are rounding to the
  1220. new_z = float(round_off) / 1000.0;
  1221. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1222. ubl.has_control_of_lcd_panel = true;
  1223. if (do_ubl_mesh_map) ubl.display_map(map_type); // show the user which point is being adjusted
  1224. lcd_implementation_clear();
  1225. lcd_mesh_edit_setup(new_z);
  1226. do {
  1227. new_z = lcd_mesh_edit();
  1228. idle();
  1229. } while (!ubl_lcd_clicked());
  1230. lcd_return_to_status();
  1231. ubl.has_control_of_lcd_panel = true; // There is a race condition for the Encoder Wheel getting clicked.
  1232. // It could get detected in lcd_mesh_edit (actually _lcd_mesh_fine_tune)
  1233. // or here.
  1234. const millis_t nxt = millis() + 1500UL;
  1235. while (ubl_lcd_clicked()) { // debounce and watch for abort
  1236. idle();
  1237. if (ELAPSED(millis(), nxt)) {
  1238. lcd_return_to_status();
  1239. //SERIAL_PROTOCOLLNPGM("\nFine Tuning of Mesh Stopped.");
  1240. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  1241. LCD_MESSAGEPGM("Mesh Editing Stopped");
  1242. while (ubl_lcd_clicked()) idle();
  1243. goto FINE_TUNE_EXIT;
  1244. }
  1245. }
  1246. safe_delay(20); // We don't want any switch noise.
  1247. ubl.z_values[location.x_index][location.y_index] = new_z;
  1248. lcd_implementation_clear();
  1249. } while (location.x_index >= 0 && location.y_index >= 0 && (--repetition_cnt>0));
  1250. FINE_TUNE_EXIT:
  1251. ubl.has_control_of_lcd_panel = false;
  1252. KEEPALIVE_STATE(IN_HANDLER);
  1253. if (do_ubl_mesh_map) ubl.display_map(map_type);
  1254. restore_ubl_active_state_and_leave();
  1255. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  1256. do_blocking_move_to_xy(lx, ly);
  1257. LCD_MESSAGEPGM("Done Editing Mesh");
  1258. SERIAL_ECHOLNPGM("Done Editing Mesh");
  1259. }
  1260. void tilt_mesh_based_on_probed_grid(const bool do_ubl_mesh_map) {
  1261. int8_t grid_G_index_to_xpos[grid_size], // UBL MESH X index to be probed
  1262. grid_G_index_to_ypos[grid_size], // UBL MESH Y index to be probed
  1263. i, j ,k, xCount, yCount, xi, yi; // counter variables
  1264. float z_values_G[grid_size][grid_size];
  1265. linear_fit *results;
  1266. for (yi = 0; yi < grid_size; yi++)
  1267. for (xi = 0; xi < grid_size; xi++)
  1268. z_values_G[xi][yi] = NAN;
  1269. uint8_t x_min = GRID_MAX_POINTS_X - 1,
  1270. x_max = 0,
  1271. y_min = GRID_MAX_POINTS_Y - 1,
  1272. y_max = 0;
  1273. //find min & max probeable points in the mesh
  1274. for (xCount = 0; xCount < GRID_MAX_POINTS_X; xCount++) {
  1275. for (yCount = 0; yCount < GRID_MAX_POINTS_Y; yCount++) {
  1276. if (WITHIN(ubl.mesh_index_to_xpos[xCount], MIN_PROBE_X, MAX_PROBE_X) && WITHIN(ubl.mesh_index_to_ypos[yCount], MIN_PROBE_Y, MAX_PROBE_Y)) {
  1277. NOMORE(x_min, xCount);
  1278. NOLESS(x_max, xCount);
  1279. NOMORE(y_min, yCount);
  1280. NOLESS(y_max, yCount);
  1281. }
  1282. }
  1283. }
  1284. if (x_max - x_min + 1 < grid_size || y_max - y_min + 1 < grid_size) {
  1285. SERIAL_ECHOPAIR("ERROR - probeable UBL MESH smaller than grid - X points: ", x_max - x_min + 1);
  1286. SERIAL_ECHOPAIR(" Y points: ", y_max - y_min + 1);
  1287. SERIAL_ECHOLNPAIR(" grid: ", grid_size);
  1288. return;
  1289. }
  1290. // populate X matrix
  1291. for (xi = 0; xi < grid_size; xi++) {
  1292. grid_G_index_to_xpos[xi] = x_min + xi * (x_max - x_min) / (grid_size - 1);
  1293. if (xi > 0 && grid_G_index_to_xpos[xi - 1] == grid_G_index_to_xpos[xi]) {
  1294. grid_G_index_to_xpos[xi] = grid_G_index_to_xpos[xi - 1] + 1;
  1295. }
  1296. }
  1297. // populate Y matrix
  1298. for (yi = 0; yi < grid_size; yi++) {
  1299. grid_G_index_to_ypos[yi] = y_min + yi * (y_max - y_min) / (grid_size - 1);
  1300. if (yi > 0 && grid_G_index_to_ypos[yi - 1] == grid_G_index_to_ypos[yi]) {
  1301. grid_G_index_to_ypos[yi] = grid_G_index_to_ypos[yi - 1] + 1;
  1302. }
  1303. }
  1304. ubl.has_control_of_lcd_panel = true;
  1305. save_ubl_active_state_and_disable(); // we don't do bed level correction because we want the raw data when we probe
  1306. DEPLOY_PROBE();
  1307. // this is a copy of the G29 AUTO_BED_LEVELING_BILINEAR method/code
  1308. #undef PROBE_Y_FIRST
  1309. #if ENABLED(PROBE_Y_FIRST)
  1310. #define PR_OUTER_VAR xCount
  1311. #define PR_OUTER_NUM grid_size
  1312. #define PR_INNER_VAR yCount
  1313. #define PR_INNER_NUM grid_size
  1314. #else
  1315. #define PR_OUTER_VAR yCount
  1316. #define PR_OUTER_NUM grid_size
  1317. #define PR_INNER_VAR xCount
  1318. #define PR_INNER_NUM grid_size
  1319. #endif
  1320. bool zig = PR_OUTER_NUM & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  1321. // Outer loop is Y with PROBE_Y_FIRST disabled
  1322. for (PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_NUM; PR_OUTER_VAR++) {
  1323. int8_t inStart, inStop, inInc;
  1324. SERIAL_ECHOPAIR("\nPR_OUTER_VAR: ", PR_OUTER_VAR);
  1325. if (zig) { // away from origin
  1326. inStart = 0;
  1327. inStop = PR_INNER_NUM;
  1328. inInc = 1;
  1329. }
  1330. else { // towards origin
  1331. inStart = PR_INNER_NUM - 1;
  1332. inStop = -1;
  1333. inInc = -1;
  1334. }
  1335. zig ^= true; // zag
  1336. // Inner loop is Y with PROBE_Y_FIRST enabled
  1337. for (PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  1338. //SERIAL_ECHOPAIR("\nPR_INNER_VAR: ", PR_INNER_VAR);
  1339. //SERIAL_ECHOPAIR("\nCheckpoint: ", 1);
  1340. // end of G29 AUTO_BED_LEVELING_BILINEAR method/code
  1341. if (ubl_lcd_clicked()) {
  1342. //SERIAL_ECHOPAIR("\nCheckpoint: ", 2);
  1343. SERIAL_ECHOLNPGM("\nGrid only partially populated.\n");
  1344. lcd_quick_feedback();
  1345. STOW_PROBE();
  1346. //SERIAL_ECHOPAIR("\nCheckpoint: ", 3);
  1347. while (ubl_lcd_clicked()) idle();
  1348. //SERIAL_ECHOPAIR("\nCheckpoint: ", 4);
  1349. ubl.has_control_of_lcd_panel = false;
  1350. restore_ubl_active_state_and_leave();
  1351. safe_delay(50); // Debounce the Encoder wheel
  1352. return;
  1353. }
  1354. //SERIAL_ECHOPAIR("\nCheckpoint: ", 5);
  1355. const float probeX = ubl.mesh_index_to_xpos[grid_G_index_to_xpos[xCount]], //where we want the probe to be
  1356. probeY = ubl.mesh_index_to_ypos[grid_G_index_to_ypos[yCount]];
  1357. //SERIAL_ECHOPAIR("\nCheckpoint: ", 6);
  1358. const float measured_z = probe_pt(LOGICAL_X_POSITION(probeX), LOGICAL_Y_POSITION(probeY), code_seen('E'), (code_seen('V') && code_has_value()) ? code_value_int() : 0); // takes into account the offsets
  1359. //SERIAL_ECHOPAIR("\nmeasured_z: ", measured_z);
  1360. z_values_G[xCount][yCount] = measured_z;
  1361. //SERIAL_ECHOLNPGM("\nFine Tuning of Mesh Stopped.");
  1362. }
  1363. }
  1364. //SERIAL_ECHOLNPGM("\nDone probing...\n");
  1365. STOW_PROBE();
  1366. restore_ubl_active_state_and_leave();
  1367. // ?? ubl.has_control_of_lcd_panel = true;
  1368. //do_blocking_move_to_xy(ubl.mesh_index_to_xpos[grid_G_index_to_xpos[0]], ubl.mesh_index_to_ypos[grid_G_index_to_ypos[0]]);
  1369. // least squares code
  1370. double xxx5[] = { 0,50,100,150,200, 20,70,120,165,195, 0,50,100,150,200, 0,55,100,150,200, 0,65,100,150,205 },
  1371. yyy5[] = { 0, 1, 2, 3, 4, 50, 51, 52, 53, 54, 100, 101,102,103,104, 150,151,152,153,154, 200,201,202,203,204 },
  1372. zzz5[] = { 0.01,.002,-.01,-.02,0, 0.01,.002,-.01,-.02,0, 0.01,.002,-.01,-.02,0, 0.01,.002,-.01,-.02,0, 0.01,.002,-.01,-.012,0.01},
  1373. xxx0[] = { 0.0, 0.0, 1.0 }, // Expect [0,0,0.1,0]
  1374. yyy0[] = { 0.0, 1.0, 0.0 },
  1375. zzz0[] = { 0.1, 0.1, 0.1 },
  1376. xxx[] = { 0.0, 0.0, 1.0, 1.0 }, // Expect [0.1,0,0.05,0]
  1377. yyy[] = { 0.0, 1.0, 0.0, 1.0 },
  1378. zzz[] = { 0.05, 0.05, 0.15, 0.15 };
  1379. results = lsf_linear_fit(xxx5, yyy5, zzz5, COUNT(xxx5));
  1380. SERIAL_ECHOPAIR("\nxxx5->A =", results->A);
  1381. SERIAL_ECHOPAIR("\nxxx5->B =", results->B);
  1382. SERIAL_ECHOPAIR("\nxxx5->D =", results->D);
  1383. SERIAL_EOL;
  1384. results = lsf_linear_fit(xxx0, yyy0, zzz0, COUNT(xxx0));
  1385. SERIAL_ECHOPAIR("\nxxx0->A =", results->A);
  1386. SERIAL_ECHOPAIR("\nxxx0->B =", results->B);
  1387. SERIAL_ECHOPAIR("\nxxx0->D =", results->D);
  1388. SERIAL_EOL;
  1389. results = lsf_linear_fit(xxx, yyy, zzz, COUNT(xxx));
  1390. SERIAL_ECHOPAIR("\nxxx->A =", results->A);
  1391. SERIAL_ECHOPAIR("\nxxx->B =", results->B);
  1392. SERIAL_ECHOPAIR("\nxxx->D =", results->D);
  1393. SERIAL_EOL;
  1394. } // end of tilt_mesh_based_on_probed_grid()
  1395. #endif // AUTO_BED_LEVELING_UBL