forked from MarlinFirmware/Marlin
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathubl_G29.cpp
More file actions
1778 lines (1479 loc) · 69.6 KB
/
ubl_G29.cpp
File metadata and controls
1778 lines (1479 loc) · 69.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "../../../inc/MarlinConfig.h"
#if ENABLED(AUTO_BED_LEVELING_UBL)
#include "../bedlevel.h"
#include "../../../MarlinCore.h"
#include "../../../HAL/shared/eeprom_api.h"
#include "../../../libs/hex_print.h"
#include "../../../module/settings.h"
#include "../../../lcd/marlinui.h"
#include "../../../module/stepper.h"
#include "../../../module/planner.h"
#include "../../../module/motion.h"
#include "../../../module/probe.h"
#include "../../../gcode/gcode.h"
#include "../../../libs/least_squares_fit.h"
#if HAS_MULTI_HOTEND
#include "../../../module/tool_change.h"
#endif
#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE)
#include "../../../core/debug_out.h"
#if ENABLED(EXTENSIBLE_UI)
#include "../../../lcd/extui/ui_api.h"
#endif
#include <math.h>
#define UBL_G29_P31
#if HAS_LCD_MENU
bool unified_bed_leveling::lcd_map_control = false;
void unified_bed_leveling::steppers_were_disabled() {
if (lcd_map_control) {
lcd_map_control = false;
ui.defer_status_screen(false);
}
}
void ubl_map_screen();
#endif
#define SIZE_OF_LITTLE_RAISE 1
#define BIG_RAISE_NOT_NEEDED 0
int unified_bed_leveling::g29_verbose_level,
unified_bed_leveling::g29_phase_value,
unified_bed_leveling::g29_repetition_cnt,
unified_bed_leveling::g29_storage_slot = 0,
unified_bed_leveling::g29_map_type;
bool unified_bed_leveling::g29_c_flag;
float unified_bed_leveling::g29_card_thickness = 0,
unified_bed_leveling::g29_constant = 0;
xy_bool_t unified_bed_leveling::xy_seen;
xy_pos_t unified_bed_leveling::g29_pos;
#if HAS_BED_PROBE
int unified_bed_leveling::g29_grid_size;
#endif
/**
* G29: Unified Bed Leveling by Roxy
*
* Parameters understood by this leveling system:
*
* A Activate Activate the Unified Bed Leveling system.
*
* B # Business Use the 'Business Card' mode of the Manual Probe subsystem with P2.
* Note: A non-compressible Spark Gap feeler gauge is recommended over a business card.
* In this mode of G29 P2, a business or index card is used as a shim that the nozzle can
* grab onto as it is lowered. In principle, the nozzle-bed distance is the same when the
* same resistance is felt in the shim. You can omit the numerical value on first invocation
* of G29 P2 B to measure shim thickness. Subsequent use of 'B' will apply the previously-
* measured thickness by default.
*
* C Continue G29 P1 C continues the generation of a partially-constructed Mesh without invalidating
* previous measurements.
*
* C G29 P2 C tells the Manual Probe subsystem to not use the current nozzle
* location in its search for the closest unmeasured Mesh Point. Instead, attempt to
* start at one end of the uprobed points and Continue sequentially.
*
* G29 P3 C specifies the Constant for the fill. Otherwise, uses a "reasonable" value.
*
* C Current G29 Z C uses the Current location (instead of bed center or nearest edge).
*
* D Disable Disable the Unified Bed Leveling system.
*
* E Stow_probe Stow the probe after each sampled point.
*
* F # Fade Fade the amount of Mesh Based Compensation over a specified height. At the
* specified height, no correction is applied and natural printer kenimatics take over. If no
* number is specified for the command, 10mm is assumed to be reasonable.
*
* H # Height With P2, 'H' specifies the Height to raise the nozzle after each manual probe of the bed.
* If omitted, the nozzle will raise by Z_CLEARANCE_BETWEEN_PROBES.
*
* H # Offset With P4, 'H' specifies the Offset above the mesh height to place the nozzle.
* If omitted, Z_CLEARANCE_BETWEEN_PROBES will be used.
*
* I # Invalidate Invalidate the specified number of Mesh Points near the given 'X' 'Y'. If X or Y are omitted,
* the nozzle location is used. If no 'I' value is given, only the point nearest to the location
* is invalidated. Use 'T' to produce a map afterward. This command is useful to invalidate a
* portion of the Mesh so it can be adjusted using other UBL tools. When attempting to invalidate
* an isolated bad mesh point, the 'T' option shows the nozzle position in the Mesh with (#). You
* can move the nozzle around and use this feature to select the center of the area (or cell) to
* invalidate.
*
* J # Grid Perform a Grid Based Leveling of the current Mesh using a grid with n points on a side.
* Not specifying a grid size will invoke the 3-Point leveling function.
*
* L Load Load Mesh from the previously activated location in the EEPROM.
*
* L # Load Load Mesh from the specified location in the EEPROM. Set this location as activated
* for subsequent Load and Store operations.
*
* The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will
* start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with
* each additional Phase that processes it.
*
* P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the
* 3D Printer to the same state it was in before the Unified Bed Leveling Compensation
* was turned on. Setting the entire Mesh to Zero is a special case that allows
* a subsequent G or T leveling operation for backward compatibility.
*
* P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using
* the Z-Probe. Usually the probe can't reach all areas that the nozzle can reach. For delta
* printers only the areas where the probe and nozzle can both reach will be automatically probed.
*
* Unreachable points will be handled in Phase 2 and Phase 3.
*
* Use 'C' to leave the previous mesh intact and automatically probe needed points. This allows you
* to invalidate parts of the Mesh but still use Automatic Probing.
*
* The 'X' and 'Y' parameters prioritize where to try and measure points. If omitted, the current
* probe position is used.
*
* Use 'T' (Topology) to generate a report of mesh generation.
*
* P1 will suspend Mesh generation if the controller button is held down. Note that you may need
* to press and hold the switch for several seconds if moves are underway.
*
* P2 Phase 2 Probe unreachable points.
*
* Use 'H' to set the height between Mesh points. If omitted, Z_CLEARANCE_BETWEEN_PROBES is used.
* Smaller values will be quicker. Move the nozzle down till it barely touches the bed. Make sure the
* nozzle is clean and unobstructed. Use caution and move slowly. This can damage your printer!
* (Uses SIZE_OF_LITTLE_RAISE mm if the nozzle is moving less than BIG_RAISE_NOT_NEEDED mm.)
*
* The 'H' value can be negative if the Mesh dips in a large area. Press and hold the
* controller button to terminate the current Phase 2 command. You can then re-issue "G29 P 2"
* with an 'H' parameter more suitable for the area you're manually probing. Note that the command
* tries to start in a corner of the bed where movement will be predictable. Override the distance
* calculation location with the X and Y parameters. You can print a Mesh Map (G29 T) to see where
* the mesh is invalidated and where the nozzle needs to move to complete the command. Use 'C' to
* indicate that the search should be based on the current position.
*
* The 'B' parameter for this command is described above. It places the manual probe subsystem into
* Business Card mode where the thickness of a business card is measured and then used to accurately
* set the nozzle height in all manual probing for the duration of the command. A Business card can
* be used, but you'll get better results with a flexible Shim that doesn't compress. This makes it
* easier to produce similar amounts of force and get more accurate measurements. Google if you're
* not sure how to use a shim.
*
* The 'T' (Map) parameter helps track Mesh building progress.
*
* NOTE: P2 requires an LCD controller!
*
* P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. There are two different paths to
* go down:
*
* - If a 'C' constant is specified, the closest invalid mesh points to the nozzle will be filled,
* and a repeat count can then also be specified with 'R'.
*
* - Leaving out 'C' invokes Smart Fill, which scans the mesh from the edges inward looking for
* invalid mesh points. Adjacent points are used to determine the bed slope. If the bed is sloped
* upward from the invalid point, it takes the value of the nearest point. If sloped downward, it's
* replaced by a value that puts all three points in a line. This version of G29 P3 is a quick, easy
* and (usually) safe way to populate unprobed mesh regions before continuing to G26 Mesh Validation
* Pattern. Note that this populates the mesh with unverified values. Pay attention and use caution.
*
* P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assumes the existence of
* an LCD Panel. It is possible to fine tune the mesh without an LCD Panel using
* G42 and M421. See the UBL documentation for further details.
*
* Phase 4 is meant to be used with G26 Mesh Validation to fine tune the mesh by direct editing
* of Mesh Points. Raise and lower points to fine tune the mesh until it gives consistently reliable
* adhesion.
*
* P4 moves to the closest Mesh Point (and/or the given X Y), raises the nozzle above the mesh height
* by the given 'H' offset (or default 0), and waits while the controller is used to adjust the nozzle
* height. On click the displayed height is saved in the mesh.
*
* Start Phase 4 at a specific location with X and Y. Adjust a specific number of Mesh Points with
* the 'R' (Repeat) parameter. (If 'R' is left out, the whole matrix is assumed.) This command can be
* terminated early (e.g., after editing the area of interest) by pressing and holding the encoder button.
*
* The general form is G29 P4 [R points] [X position] [Y position]
*
* The H [offset] parameter is useful if a shim is used to fine-tune the mesh. For a 0.4mm shim the
* command would be G29 P4 H0.4. The nozzle is moved to the shim height, you adjust height to the shim,
* and on click the height minus the shim thickness will be saved in the mesh.
*
* !!Use with caution, as a very poor mesh could cause the nozzle to crash into the bed!!
*
* NOTE: P4 is not available unless you have LCD support enabled!
*
* P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and
* work with the Mesh if it is Mean Adjusted. You can specify a C parameter to
* Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically
* execute a G29 P6 C <mean height>.
*
* P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified
* with the C parameter. Being able to adjust the height of a Mesh is useful tool. It
* can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally,
* you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring
* 0.000 at the Z Home location.
*
* Q Test Load specified Test Pattern to assist in checking correct operation of system. This
* command is not anticipated to be of much value to the typical user. It is intended
* for developers to help them verify correct operation of the Unified Bed Leveling System.
*
* R # Repeat Repeat this command the specified number of times. If no number is specified the
* command will be repeated GRID_MAX_POINTS_X * GRID_MAX_POINTS_Y times.
*
* S Store Store the current Mesh in the Activated area of the EEPROM. It will also store the
* current state of the Unified Bed Leveling system in the EEPROM.
*
* S # Store Store the current Mesh at the specified location in EEPROM. Activate this location
* for subsequent Load and Store operations. Valid storage slot numbers begin at 0 and
* extend to a limit related to the available EEPROM storage.
*
* S -1 Store Print the current Mesh as G-code that can be used to restore the mesh anytime.
*
* T Topology Display the Mesh Map Topology.
* 'T' can be used alone (e.g., G29 T) or in combination with most of the other commands.
* This option works with all Phase commands (e.g., G29 P4 R 5 T X 50 Y100 C -.1 O)
* This parameter can also specify a Map Type. T0 (the default) is user-readable. T1
* is suitable to paste into a spreadsheet for a 3D graph of the mesh.
*
* U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds.
* Only used for G29 P1 T U. This speeds up the probing of the edge of the bed. Useful
* when the entire bed doesn't need to be probed because it will be adjusted.
*
* V # Verbosity Set the verbosity level (0-4) for extra details. (Default 0)
*
* X # X Location for this command
*
* Y # Y Location for this command
*
* With UBL_DEVEL_DEBUGGING:
*
* K # Kompare Kompare current Mesh with stored Mesh #, replacing current Mesh with the result.
* This command literally performs a diff between two Meshes.
*
* Q-1 Dump EEPROM Dump the UBL contents stored in EEPROM as HEX format. Useful for developers to help
* verify correct operation of the UBL.
*
* W What? Display valuable UBL data.
*
*
* Release Notes:
* You MUST do M502, M500 to initialize the storage. Failure to do this will cause all
* kinds of problems. Enabling EEPROM Storage is required.
*
* When you do a G28 and G29 P1 to automatically build your first mesh, you are going to notice that
* UBL probes points increasingly further from the starting location. (The starting location defaults
* to the center of the bed.) In contrast, ABL and MBL follow a zigzag pattern. The spiral pattern is
* especially better for Delta printers, since it populates the center of the mesh first, allowing for
* a quicker test print to verify settings. You don't need to populate the entire mesh to use it.
* After all, you don't want to spend a lot of time generating a mesh only to realize the resolution
* or probe offsets are incorrect. Mesh-generation gathers points starting closest to the nozzle unless
* an (X,Y) coordinate pair is given.
*
* Unified Bed Leveling uses a lot of EEPROM storage to hold its data, and it takes some effort to get
* the mesh just right. To prevent this valuable data from being destroyed as the EEPROM structure
* evolves, UBL stores all mesh data at the end of EEPROM.
*
* UBL is founded on Edward Patel's Mesh Bed Leveling code. A big 'Thanks!' to him and the creators of
* 3-Point and Grid Based leveling. Combining their contributions we now have the functionality and
* features of all three systems combined.
*/
void unified_bed_leveling::G29() {
bool probe_deployed = false;
if (g29_parameter_parsing()) return; // Abort on parameter error
const int8_t p_val = parser.intval('P', -1);
const bool may_move = p_val == 1 || p_val == 2 || p_val == 4 || parser.seen('J');
TERN_(HAS_MULTI_HOTEND, const uint8_t old_tool_index = active_extruder);
// Check for commands that require the printer to be homed
if (may_move) {
planner.synchronize();
if (axes_should_home()) gcode.home_all_axes();
TERN_(HAS_MULTI_HOTEND, if (active_extruder) tool_change(0));
}
// Invalidate Mesh Points. This command is a little bit asymmetrical because
// it directly specifies the repetition count and does not use the 'R' parameter.
if (parser.seen('I')) {
uint8_t cnt = 0;
g29_repetition_cnt = parser.has_value() ? parser.value_int() : 1;
if (g29_repetition_cnt >= GRID_MAX_POINTS) {
set_all_mesh_points_to_value(NAN);
}
else {
while (g29_repetition_cnt--) {
if (cnt > 20) { cnt = 0; idle(); }
const mesh_index_pair closest = find_closest_mesh_point_of_type(REAL, g29_pos);
const xy_int8_t &cpos = closest.pos;
if (cpos.x < 0) {
// No more REAL mesh points to invalidate, so we ASSUME the user
// meant to invalidate the ENTIRE mesh, which cannot be done with
// find_closest_mesh_point loop which only returns REAL points.
set_all_mesh_points_to_value(NAN);
SERIAL_ECHOLNPGM("Entire Mesh invalidated.\n");
break; // No more invalid Mesh Points to populate
}
z_values[cpos.x][cpos.y] = NAN;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(cpos, 0.0f));
cnt++;
}
}
SERIAL_ECHOLNPGM("Locations invalidated.\n");
}
if (parser.seen('Q')) {
const int test_pattern = parser.has_value() ? parser.value_int() : -99;
if (!WITHIN(test_pattern, -1, 2)) {
SERIAL_ECHOLNPGM("Invalid test_pattern value. (-1 to 2)\n");
return;
}
SERIAL_ECHOLNPGM("Loading test_pattern values.\n");
switch (test_pattern) {
#if ENABLED(UBL_DEVEL_DEBUGGING)
case -1:
g29_eeprom_dump();
break;
#endif
case 0:
GRID_LOOP(x, y) { // Create a bowl shape similar to a poorly-calibrated Delta
const float p1 = 0.5f * (GRID_MAX_POINTS_X) - x,
p2 = 0.5f * (GRID_MAX_POINTS_Y) - y;
z_values[x][y] += 2.0f * HYPOT(p1, p2);
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
break;
case 1:
LOOP_L_N(x, GRID_MAX_POINTS_X) { // Create a diagonal line several Mesh cells thick that is raised
z_values[x][x] += 9.999f;
z_values[x][x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1] += 9.999f; // We want the altered line several mesh points thick
#if ENABLED(EXTENSIBLE_UI)
ExtUI::onMeshUpdate(x, x, z_values[x][x]);
ExtUI::onMeshUpdate(x, (x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1), z_values[x][x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1]);
#endif
}
break;
case 2:
// Allow the user to specify the height because 10mm is a little extreme in some cases.
for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in
for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) { // the center of the bed
z_values[x][y] += parser.seen('C') ? g29_constant : 9.99f;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
break;
}
}
#if HAS_BED_PROBE
if (parser.seen('J')) {
save_ubl_active_state_and_disable();
tilt_mesh_based_on_probed_grid(g29_grid_size == 0); // Zero size does 3-Point
restore_ubl_active_state_and_leave();
#if ENABLED(UBL_G29_J_RECENTER)
do_blocking_move_to_xy(0.5f * ((MESH_MIN_X) + (MESH_MAX_X)), 0.5f * ((MESH_MIN_Y) + (MESH_MAX_Y)));
#endif
report_current_position();
probe_deployed = true;
}
#endif // HAS_BED_PROBE
if (parser.seen('P')) {
if (WITHIN(g29_phase_value, 0, 1) && storage_slot == -1) {
storage_slot = 0;
SERIAL_ECHOLNPGM("Default storage slot 0 selected.");
}
switch (g29_phase_value) {
case 0:
//
// Zero Mesh Data
//
reset();
SERIAL_ECHOLNPGM("Mesh zeroed.");
break;
#if HAS_BED_PROBE
case 1: {
//
// Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
//
if (!parser.seen('C')) {
invalidate();
SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh.");
}
if (g29_verbose_level > 1) {
SERIAL_ECHOPAIR("Probing around (", g29_pos.x);
SERIAL_CHAR(',');
SERIAL_DECIMAL(g29_pos.y);
SERIAL_ECHOLNPGM(").\n");
}
const xy_pos_t near_probe_xy = g29_pos + probe.offset_xy;
probe_entire_mesh(near_probe_xy, parser.seen('T'), parser.seen('E'), parser.seen('U'));
report_current_position();
probe_deployed = true;
} break;
#endif // HAS_BED_PROBE
case 2: {
#if HAS_LCD_MENU
//
// Manually Probe Mesh in areas that can't be reached by the probe
//
SERIAL_ECHOLNPGM("Manually probing unreachable points.");
do_z_clearance(Z_CLEARANCE_BETWEEN_PROBES);
if (parser.seen('C') && !xy_seen) {
/**
* Use a good default location for the path.
* The flipped > and < operators in these comparisons is intentional.
* It should cause the probed points to follow a nice path on Cartesian printers.
* It may make sense to have Delta printers default to the center of the bed.
* Until that is decided, this can be forced with the X and Y parameters.
*/
g29_pos.set(
#if IS_KINEMATIC
X_HOME_POS, Y_HOME_POS
#else
probe.offset_xy.x > 0 ? X_BED_SIZE : 0,
probe.offset_xy.y < 0 ? Y_BED_SIZE : 0
#endif
);
}
if (parser.seen('B')) {
g29_card_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness();
if (ABS(g29_card_thickness) > 1.5f) {
SERIAL_ECHOLNPGM("?Error in Business Card measurement.");
return;
}
probe_deployed = true;
}
if (!position_is_reachable(g29_pos)) {
SERIAL_ECHOLNPGM("XY outside printable radius.");
return;
}
const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES);
manually_probe_remaining_mesh(g29_pos, height, g29_card_thickness, parser.seen('T'));
SERIAL_ECHOLNPGM("G29 P2 finished.");
report_current_position();
#else
SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present.");
return;
#endif
} break;
case 3: {
/**
* Populate invalid mesh areas. Proceed with caution.
* Two choices are available:
* - Specify a constant with the 'C' parameter.
* - Allow 'G29 P3' to choose a 'reasonable' constant.
*/
if (g29_c_flag) {
if (g29_repetition_cnt >= GRID_MAX_POINTS) {
set_all_mesh_points_to_value(g29_constant);
}
else {
while (g29_repetition_cnt--) { // this only populates reachable mesh points near
const mesh_index_pair closest = find_closest_mesh_point_of_type(INVALID, g29_pos);
const xy_int8_t &cpos = closest.pos;
if (cpos.x < 0) {
// No more REAL INVALID mesh points to populate, so we ASSUME
// user meant to populate ALL INVALID mesh points to value
GRID_LOOP(x, y) if (isnan(z_values[x][y])) z_values[x][y] = g29_constant;
break; // No more invalid Mesh Points to populate
}
else {
z_values[cpos.x][cpos.y] = g29_constant;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(cpos, g29_constant));
}
}
}
}
else {
const float cvf = parser.value_float();
switch ((int)truncf(cvf * 10.0f) - 30) { // 3.1 -> 1
#if ENABLED(UBL_G29_P31)
case 1: {
// P3.1 use least squares fit to fill missing mesh values
// P3.10 zero weighting for distance, all grid points equal, best fit tilted plane
// P3.11 10X weighting for nearest grid points versus farthest grid points
// P3.12 100X distance weighting
// P3.13 1000X distance weighting, approaches simple average of nearest points
const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345
weight_factor = weight_power ? POW(10.0f, weight_power) : 0;
smart_fill_wlsf(weight_factor);
}
break;
#endif
case 0: // P3 or P3.0
default: // and anything P3.x that's not P3.1
smart_fill_mesh(); // Do a 'Smart' fill using nearby known values
break;
}
}
break;
}
case 4: // Fine Tune (i.e., Edit) the Mesh
#if HAS_LCD_MENU
fine_tune_mesh(g29_pos, parser.seen('T'));
#else
SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present.");
return;
#endif
break;
case 5: adjust_mesh_to_mean(g29_c_flag, g29_constant); break;
case 6: shift_mesh_height(); break;
}
}
#if ENABLED(UBL_DEVEL_DEBUGGING)
//
// Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
// good to have the extra information. Soon... we prune this to just a few items
//
if (parser.seen('W')) g29_what_command();
//
// When we are fully debugged, this may go away. But there are some valid
// use cases for the users. So we can wait and see what to do with it.
//
if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
g29_compare_current_mesh_to_stored_mesh();
#endif // UBL_DEVEL_DEBUGGING
//
// Load a Mesh from the EEPROM
//
if (parser.seen('L')) { // Load Current Mesh Data
g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
int16_t a = settings.calc_num_meshes();
if (!a) {
SERIAL_ECHOLNPGM("?EEPROM storage not available.");
return;
}
if (!WITHIN(g29_storage_slot, 0, a - 1)) {
SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
return;
}
settings.load_mesh(g29_storage_slot);
storage_slot = g29_storage_slot;
SERIAL_ECHOLNPGM("Done.");
}
//
// Store a Mesh in the EEPROM
//
if (parser.seen('S')) { // Store (or Save) Current Mesh Data
g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
if (g29_storage_slot == -1) // Special case, the user wants to 'Export' the mesh to the
return report_current_mesh(); // host program to be saved on the user's computer
int16_t a = settings.calc_num_meshes();
if (!a) {
SERIAL_ECHOLNPGM("?EEPROM storage not available.");
goto LEAVE;
}
if (!WITHIN(g29_storage_slot, 0, a - 1)) {
SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
goto LEAVE;
}
settings.store_mesh(g29_storage_slot);
storage_slot = g29_storage_slot;
SERIAL_ECHOLNPGM("Done.");
}
if (parser.seen('T'))
display_map(g29_map_type);
LEAVE:
#if HAS_LCD_MENU
ui.reset_alert_level();
ui.quick_feedback();
ui.reset_status();
ui.release();
#endif
#ifdef Z_PROBE_END_SCRIPT
if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
if (probe_deployed) {
planner.synchronize();
gcode.process_subcommands_now_P(PSTR(Z_PROBE_END_SCRIPT));
}
#else
UNUSED(probe_deployed);
#endif
TERN_(HAS_MULTI_HOTEND, tool_change(old_tool_index));
return;
}
void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const float value) {
float sum = 0;
int n = 0;
GRID_LOOP(x, y)
if (!isnan(z_values[x][y])) {
sum += z_values[x][y];
n++;
}
const float mean = sum / n;
//
// Sum the squares of difference from mean
//
float sum_of_diff_squared = 0;
GRID_LOOP(x, y)
if (!isnan(z_values[x][y]))
sum_of_diff_squared += sq(z_values[x][y] - mean);
SERIAL_ECHOLNPAIR("# of samples: ", n);
SERIAL_ECHOLNPAIR_F("Mean Mesh Height: ", mean, 6);
const float sigma = SQRT(sum_of_diff_squared / (n + 1));
SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6);
if (cflag)
GRID_LOOP(x, y)
if (!isnan(z_values[x][y])) {
z_values[x][y] -= mean + value;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
}
void unified_bed_leveling::shift_mesh_height() {
GRID_LOOP(x, y)
if (!isnan(z_values[x][y])) {
z_values[x][y] += g29_constant;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
}
#if HAS_BED_PROBE
/**
* Probe all invalidated locations of the mesh that can be reached by the probe.
* This attempts to fill in locations closest to the nozzle's start location first.
*/
void unified_bed_leveling::probe_entire_mesh(const xy_pos_t &near, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) {
probe.deploy(); // Deploy before ui.capture() to allow for PAUSE_BEFORE_DEPLOY_STOW
TERN_(HAS_LCD_MENU, ui.capture());
save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
uint8_t count = GRID_MAX_POINTS;
mesh_index_pair best;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::MESH_START));
do {
if (do_ubl_mesh_map) display_map(g29_map_type);
const int point_num = (GRID_MAX_POINTS) - count + 1;
SERIAL_ECHOLNPAIR("\nProbing mesh point ", point_num, "/", int(GRID_MAX_POINTS), ".\n");
TERN_(HAS_DISPLAY, ui.status_printf_P(0, PSTR(S_FMT " %i/%i"), GET_TEXT(MSG_PROBING_MESH), point_num, int(GRID_MAX_POINTS)));
#if HAS_LCD_MENU
if (ui.button_pressed()) {
ui.quick_feedback(false); // Preserve button state for click-and-hold
SERIAL_ECHOLNPGM("\nMesh only partially populated.\n");
ui.wait_for_release();
ui.quick_feedback();
ui.release();
probe.stow(); // Release UI before stow to allow for PAUSE_BEFORE_DEPLOY_STOW
return restore_ubl_active_state_and_leave();
}
#endif
best = do_furthest
? find_furthest_invalid_mesh_point()
: find_closest_mesh_point_of_type(INVALID, near, true);
if (best.pos.x >= 0) { // mesh point found and is reachable by probe
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::PROBE_START));
const float measured_z = probe.probe_at_point(
best.meshpos(),
stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level
);
z_values[best.pos.x][best.pos.y] = measured_z;
#if ENABLED(EXTENSIBLE_UI)
ExtUI::onMeshUpdate(best.pos, ExtUI::PROBE_FINISH);
ExtUI::onMeshUpdate(best.pos, measured_z);
#endif
}
SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
} while (best.pos.x >= 0 && --count);
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::MESH_FINISH));
// Release UI during stow to allow for PAUSE_BEFORE_DEPLOY_STOW
TERN_(HAS_LCD_MENU, ui.release());
probe.stow();
TERN_(HAS_LCD_MENU, ui.capture());
probe.move_z_after_probing();
restore_ubl_active_state_and_leave();
do_blocking_move_to_xy(
constrain(near.x - probe.offset_xy.x, MESH_MIN_X, MESH_MAX_X),
constrain(near.y - probe.offset_xy.y, MESH_MIN_Y, MESH_MAX_Y)
);
}
#endif // HAS_BED_PROBE
#if HAS_LCD_MENU
typedef void (*clickFunc_t)();
bool click_and_hold(const clickFunc_t func=nullptr) {
if (ui.button_pressed()) {
ui.quick_feedback(false); // Preserve button state for click-and-hold
const millis_t nxt = millis() + 1500UL;
while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag!
idle(); // idle, of course
if (ELAPSED(millis(), nxt)) { // After 1.5 seconds
ui.quick_feedback();
if (func) (*func)();
ui.wait_for_release();
return true;
}
}
}
serial_delay(15);
return false;
}
void unified_bed_leveling::move_z_with_encoder(const float &multiplier) {
ui.wait_for_release();
while (!ui.button_pressed()) {
idle();
gcode.reset_stepper_timeout(); // Keep steppers powered
if (encoder_diff) {
do_blocking_move_to_z(current_position.z + float(encoder_diff) * multiplier);
encoder_diff = 0;
}
}
}
float unified_bed_leveling::measure_point_with_encoder() {
KEEPALIVE_STATE(PAUSED_FOR_USER);
move_z_with_encoder(0.01f);
return current_position.z;
}
static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); }
float unified_bed_leveling::measure_business_card_thickness() {
ui.capture();
save_ubl_active_state_and_disable(); // Disable bed level correction for probing
do_blocking_move_to(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)), MANUAL_PROBE_START_Z);
//, _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f);
planner.synchronize();
SERIAL_ECHOPGM("Place shim under nozzle");
LCD_MESSAGEPGM(MSG_UBL_BC_INSERT);
ui.return_to_status();
echo_and_take_a_measurement();
const float z1 = measure_point_with_encoder();
do_blocking_move_to_z(current_position.z + SIZE_OF_LITTLE_RAISE);
planner.synchronize();
SERIAL_ECHOPGM("Remove shim");
LCD_MESSAGEPGM(MSG_UBL_BC_REMOVE);
echo_and_take_a_measurement();
const float z2 = measure_point_with_encoder();
do_blocking_move_to_z(current_position.z + Z_CLEARANCE_BETWEEN_PROBES);
const float thickness = ABS(z1 - z2);
if (g29_verbose_level > 1) {
SERIAL_ECHOPAIR_F("Business Card is ", thickness, 4);
SERIAL_ECHOLNPGM("mm thick.");
}
restore_ubl_active_state_and_leave();
return thickness;
}
void unified_bed_leveling::manually_probe_remaining_mesh(const xy_pos_t &pos, const float &z_clearance, const float &thick, const bool do_ubl_mesh_map) {
ui.capture();
save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
do_blocking_move_to_xy_z(current_position, z_clearance);
ui.return_to_status();
mesh_index_pair location;
const xy_int8_t &lpos = location.pos;
do {
location = find_closest_mesh_point_of_type(INVALID, pos);
// It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
if (!location.valid()) continue;
const xyz_pos_t ppos = {
mesh_index_to_xpos(lpos.x),
mesh_index_to_ypos(lpos.y),
Z_CLEARANCE_BETWEEN_PROBES
};
if (!position_is_reachable(ppos)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points)
LCD_MESSAGEPGM(MSG_UBL_MOVING_TO_NEXT);
do_blocking_move_to(ppos);
do_z_clearance(z_clearance);
KEEPALIVE_STATE(PAUSED_FOR_USER);
ui.capture();
if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
serialprintPGM(parser.seen('B') ? GET_TEXT(MSG_UBL_BC_INSERT) : GET_TEXT(MSG_UBL_BC_INSERT2));
const float z_step = 0.01f; // existing behavior: 0.01mm per click, occasionally step
//const float z_step = planner.steps_to_mm[Z_AXIS]; // approx one step each click
move_z_with_encoder(z_step);
if (click_and_hold()) {
SERIAL_ECHOLNPGM("\nMesh only partially populated.");
do_z_clearance(Z_CLEARANCE_DEPLOY_PROBE);
return restore_ubl_active_state_and_leave();
}
z_values[lpos.x][lpos.y] = current_position.z - thick;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, z_values[lpos.x][lpos.y]));
if (g29_verbose_level > 2)
SERIAL_ECHOLNPAIR_F("Mesh Point Measured at: ", z_values[lpos.x][lpos.y], 6);
SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
} while (location.valid());
if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
restore_ubl_active_state_and_leave();
do_blocking_move_to_xy_z(pos, Z_CLEARANCE_DEPLOY_PROBE);
}
inline void set_message_with_feedback(PGM_P const msg_P) {
ui.set_status_P(msg_P);
ui.quick_feedback();
}
void abort_fine_tune() {
ui.return_to_status();
do_z_clearance(Z_CLEARANCE_BETWEEN_PROBES);
set_message_with_feedback(GET_TEXT(MSG_EDITING_STOPPED));
}
void unified_bed_leveling::fine_tune_mesh(const xy_pos_t &pos, const bool do_ubl_mesh_map) {
if (!parser.seen('R')) // fine_tune_mesh() is special. If no repetition count flag is specified
g29_repetition_cnt = 1; // do exactly one mesh location. Otherwise use what the parser decided.
#if ENABLED(UBL_MESH_EDIT_MOVES_Z)
const float h_offset = parser.seenval('H') ? parser.value_linear_units() : 0;
if (!WITHIN(h_offset, 0, 10)) {
SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n");
return;
}
#endif
mesh_index_pair location;
if (!position_is_reachable(pos)) {
SERIAL_ECHOLNPGM("(X,Y) outside printable radius.");
return;
}
save_ubl_active_state_and_disable();
LCD_MESSAGEPGM(MSG_UBL_FINE_TUNE_MESH);
ui.capture(); // Take over control of the LCD encoder
do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES); // Move to the given XY with probe clearance
TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset
MeshFlags done_flags{0};
const xy_int8_t &lpos = location.pos;
do {
location = find_closest_mesh_point_of_type(SET_IN_BITMAP, pos, false, &done_flags);
if (lpos.x < 0) break; // Stop when there are no more reachable points
done_flags.mark(lpos); // Mark this location as 'adjusted' so a new
// location is used on the next loop
const xyz_pos_t raw = {
mesh_index_to_xpos(lpos.x),
mesh_index_to_ypos(lpos.y),
Z_CLEARANCE_BETWEEN_PROBES
};
if (!position_is_reachable(raw)) break; // SHOULD NOT OCCUR (find_closest_mesh_point_of_type only returns reachable)
do_blocking_move_to(raw); // Move the nozzle to the edit point with probe clearance
TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset before editing
KEEPALIVE_STATE(PAUSED_FOR_USER);
if (do_ubl_mesh_map) display_map(g29_map_type); // Display the current point
#if IS_TFTGLCD_PANEL