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

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