Subversion Repositories Tronxy-X3A-Marlin

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 ron 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
 
23
/**
24
 * Marlin Firmware -- G26 - Mesh Validation Tool
25
 */
26
 
27
#include "MarlinConfig.h"
28
 
29
#if ENABLED(G26_MESH_VALIDATION)
30
 
31
  #include "Marlin.h"
32
  #include "planner.h"
33
  #include "stepper.h"
34
  #include "temperature.h"
35
  #include "ultralcd.h"
36
  #include "parser.h"
37
  #include "serial.h"
38
  #include "bitmap_flags.h"
39
 
40
  #if ENABLED(MESH_BED_LEVELING)
41
    #include "mesh_bed_leveling.h"
42
  #elif ENABLED(AUTO_BED_LEVELING_UBL)
43
    #include "ubl.h"
44
  #endif
45
 
46
  #define EXTRUSION_MULTIPLIER 1.0
47
  #define RETRACTION_MULTIPLIER 1.0
48
  #define PRIME_LENGTH 10.0
49
  #define OOZE_AMOUNT 0.3
50
 
51
  #define INTERSECTION_CIRCLE_RADIUS 5
52
  #define CROSSHAIRS_SIZE 3
53
 
54
  #if CROSSHAIRS_SIZE >= INTERSECTION_CIRCLE_RADIUS
55
    #error "CROSSHAIRS_SIZE must be less than INTERSECTION_CIRCLE_RADIUS."
56
  #endif
57
 
58
  #define G26_OK false
59
  #define G26_ERR true
60
 
61
  /**
62
   *   G26 Mesh Validation Tool
63
   *
64
   *   G26 is a Mesh Validation Tool intended to provide support for the Marlin Unified Bed Leveling System.
65
   *   In order to fully utilize and benefit from the Marlin Unified Bed Leveling System an accurate Mesh must
66
   *   be defined. G29 is designed to allow the user to quickly validate the correctness of her Mesh. It will
67
   *   first heat the bed and nozzle. It will then print lines and circles along the Mesh Cell boundaries and
68
   *   the intersections of those lines (respectively).
69
   *
70
   *   This action allows the user to immediately see where the Mesh is properly defined and where it needs to
71
   *   be edited. The command will generate the Mesh lines closest to the nozzle's starting position. Alternatively
72
   *   the user can specify the X and Y position of interest with command parameters. This allows the user to
73
   *   focus on a particular area of the Mesh where attention is needed.
74
   *
75
   *   B #  Bed         Set the Bed Temperature. If not specified, a default of 60 C. will be assumed.
76
   *
77
   *   C    Current     When searching for Mesh Intersection points to draw, use the current nozzle location
78
   *                    as the base for any distance comparison.
79
   *
80
   *   D    Disable     Disable the Unified Bed Leveling System. In the normal case the user is invoking this
81
   *                    command to see how well a Mesh as been adjusted to match a print surface. In order to do
82
   *                    this the Unified Bed Leveling System is turned on by the G26 command. The D parameter
83
   *                    alters the command's normal behaviour and disables the Unified Bed Leveling System even if
84
   *                    it is on.
85
   *
86
   *   H #  Hotend      Set the Nozzle Temperature. If not specified, a default of 205 C. will be assumed.
87
   *
88
   *   F #  Filament    Used to specify the diameter of the filament being used. If not specified
89
   *                    1.75mm filament is assumed. If you are not getting acceptable results by using the
90
   *                    'correct' numbers, you can scale this number up or down a little bit to change the amount
91
   *                    of filament that is being extruded during the printing of the various lines on the bed.
92
   *
93
   *   K    Keep-On     Keep the heaters turned on at the end of the command.
94
   *
95
   *   L #  Layer       Layer height. (Height of nozzle above bed)  If not specified .20mm will be used.
96
   *
97
   *   O #  Ooooze      How much your nozzle will Ooooze filament while getting in position to print. This
98
   *                    is over kill, but using this parameter will let you get the very first 'circle' perfect
99
   *                    so you have a trophy to peel off of the bed and hang up to show how perfectly you have your
100
   *                    Mesh calibrated. If not specified, a filament length of .3mm is assumed.
101
   *
102
   *   P #  Prime       Prime the nozzle with specified length of filament. If this parameter is not
103
   *                    given, no prime action will take place. If the parameter specifies an amount, that much
104
   *                    will be purged before continuing. If no amount is specified the command will start
105
   *                    purging filament until the user provides an LCD Click and then it will continue with
106
   *                    printing the Mesh. You can carefully remove the spent filament with a needle nose
107
   *                    pliers while holding the LCD Click wheel in a depressed state. If you do not have
108
   *                    an LCD, you must specify a value if you use P.
109
   *
110
   *   Q #  Multiplier  Retraction Multiplier. Normally not needed. Retraction defaults to 1.0mm and
111
   *                    un-retraction is at 1.2mm   These numbers will be scaled by the specified amount
112
   *
113
   *   R #  Repeat      Prints the number of patterns given as a parameter, starting at the current location.
114
   *                    If a parameter isn't given, every point will be printed unless G26 is interrupted.
115
   *                    This works the same way that the UBL G29 P4 R parameter works.
116
   *
117
   *                    NOTE:  If you do not have an LCD, you -must- specify R. This is to ensure that you are
118
   *                    aware that there's some risk associated with printing without the ability to abort in
119
   *                    cases where mesh point Z value may be inaccurate. As above, if you do not include a
120
   *                    parameter, every point will be printed.
121
   *
122
   *   S #  Nozzle      Used to control the size of nozzle diameter. If not specified, a .4mm nozzle is assumed.
123
   *
124
   *   U #  Random      Randomize the order that the circles are drawn on the bed. The search for the closest
125
   *                    undrawn cicle is still done. But the distance to the location for each circle has a
126
   *                    random number of the size specified added to it. Specifying S50 will give an interesting
127
   *                    deviation from the normal behaviour on a 10 x 10 Mesh.
128
   *
129
   *   X #  X Coord.    Specify the starting location of the drawing activity.
130
   *
131
   *   Y #  Y Coord.    Specify the starting location of the drawing activity.
132
   */
133
 
134
  // External references
135
 
136
  extern Planner planner;
137
 
138
  // Private functions
139
 
140
  static uint16_t circle_flags[16], horizontal_mesh_line_flags[16], vertical_mesh_line_flags[16];
141
  float g26_e_axis_feedrate = 0.025,
142
        random_deviation = 0.0;
143
 
144
  static bool g26_retracted = false; // Track the retracted state of the nozzle so mismatched
145
                                     // retracts/recovers won't result in a bad state.
146
 
147
  static float g26_extrusion_multiplier,
148
               g26_retraction_multiplier,
149
               g26_layer_height,
150
               g26_prime_length,
151
               g26_x_pos, g26_y_pos;
152
 
153
  static int16_t g26_bed_temp,
154
                 g26_hotend_temp;
155
 
156
  static int8_t g26_prime_flag;
157
 
158
  #if ENABLED(ULTIPANEL)
159
 
160
    /**
161
     * If the LCD is clicked, cancel, wait for release, return true
162
     */
163
    bool user_canceled() {
164
      if (!is_lcd_clicked()) return false; // Return if the button isn't pressed
165
      lcd_setstatusPGM(PSTR("Mesh Validation Stopped."), 99);
166
      #if ENABLED(ULTIPANEL)
167
        lcd_quick_feedback(true);
168
      #endif
169
      wait_for_release();
170
      return true;
171
    }
172
 
173
    bool exit_from_g26() {
174
      lcd_setstatusPGM(PSTR("Leaving G26"), -1);
175
      wait_for_release();
176
      return G26_ERR;
177
    }
178
 
179
  #endif
180
 
181
  void G26_line_to_destination(const float &feed_rate) {
182
    const float save_feedrate = feedrate_mm_s;
183
    feedrate_mm_s = feed_rate;
184
    prepare_move_to_destination();  // will ultimately call ubl.line_to_destination_cartesian or ubl.prepare_linear_move_to for UBL_SEGMENTED
185
    feedrate_mm_s = save_feedrate;
186
  }
187
 
188
  void move_to(const float &rx, const float &ry, const float &z, const float &e_delta) {
189
    float feed_value;
190
    static float last_z = -999.99;
191
 
192
    bool has_xy_component = (rx != current_position[X_AXIS] || ry != current_position[Y_AXIS]); // Check if X or Y is involved in the movement.
193
 
194
    if (z != last_z) {
195
      last_z = z;
196
      feed_value = planner.max_feedrate_mm_s[Z_AXIS]/(3.0);  // Base the feed rate off of the configured Z_AXIS feed rate
197
 
198
      destination[X_AXIS] = current_position[X_AXIS];
199
      destination[Y_AXIS] = current_position[Y_AXIS];
200
      destination[Z_AXIS] = z;                          // We know the last_z==z or we wouldn't be in this block of code.
201
      destination[E_CART] = current_position[E_CART];
202
 
203
      G26_line_to_destination(feed_value);
204
      set_destination_from_current();
205
    }
206
 
207
    // Check if X or Y is involved in the movement.
208
    // Yes: a 'normal' movement. No: a retract() or recover()
209
    feed_value = has_xy_component ? PLANNER_XY_FEEDRATE() / 10.0 : planner.max_feedrate_mm_s[E_AXIS] / 1.5;
210
 
211
    if (g26_debug_flag) SERIAL_ECHOLNPAIR("in move_to() feed_value for XY:", feed_value);
212
 
213
    destination[X_AXIS] = rx;
214
    destination[Y_AXIS] = ry;
215
    destination[E_CART] += e_delta;
216
 
217
    G26_line_to_destination(feed_value);
218
    set_destination_from_current();
219
  }
220
 
221
  FORCE_INLINE void move_to(const float where[XYZE], const float &de) { move_to(where[X_AXIS], where[Y_AXIS], where[Z_AXIS], de); }
222
 
223
  void retract_filament(const float where[XYZE]) {
224
    if (!g26_retracted) { // Only retract if we are not already retracted!
225
      g26_retracted = true;
226
      move_to(where, -1.0 * g26_retraction_multiplier);
227
    }
228
  }
229
 
230
  void recover_filament(const float where[XYZE]) {
231
    if (g26_retracted) { // Only un-retract if we are retracted.
232
      move_to(where, 1.2 * g26_retraction_multiplier);
233
      g26_retracted = false;
234
    }
235
  }
236
 
237
  /**
238
   * Prime the nozzle if needed. Return true on error.
239
   */
240
  inline bool prime_nozzle() {
241
 
242
    #if ENABLED(ULTIPANEL)
243
      float Total_Prime = 0.0;
244
 
245
      if (g26_prime_flag == -1) {  // The user wants to control how much filament gets purged
246
 
247
        lcd_external_control = true;
248
        lcd_setstatusPGM(PSTR("User-Controlled Prime"), 99);
249
        lcd_chirp();
250
 
251
        set_destination_from_current();
252
 
253
        recover_filament(destination); // Make sure G26 doesn't think the filament is retracted().
254
 
255
        while (!is_lcd_clicked()) {
256
          lcd_chirp();
257
          destination[E_CART] += 0.25;
258
          #ifdef PREVENT_LENGTHY_EXTRUDE
259
            Total_Prime += 0.25;
260
            if (Total_Prime >= EXTRUDE_MAXLENGTH) return G26_ERR;
261
          #endif
262
          G26_line_to_destination(planner.max_feedrate_mm_s[E_AXIS] / 15.0);
263
          set_destination_from_current();
264
          planner.synchronize();    // Without this synchronize, the purge is more consistent,
265
                                    // but because the planner has a buffer, we won't be able
266
                                    // to stop as quickly. So we put up with the less smooth
267
                                    // action to give the user a more responsive 'Stop'.
268
 
269
          SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
270
        }
271
 
272
        wait_for_release();
273
 
274
        lcd_setstatusPGM(PSTR("Done Priming"), 99);
275
        lcd_quick_feedback(true);
276
        lcd_external_control = false;
277
      }
278
      else
279
    #endif
280
    {
281
      #if ENABLED(ULTRA_LCD)
282
        lcd_setstatusPGM(PSTR("Fixed Length Prime."), 99);
283
        lcd_quick_feedback(true);
284
      #endif
285
      set_destination_from_current();
286
      destination[E_CART] += g26_prime_length;
287
      G26_line_to_destination(planner.max_feedrate_mm_s[E_AXIS] / 15.0);
288
      set_destination_from_current();
289
      retract_filament(destination);
290
    }
291
 
292
    return G26_OK;
293
  }
294
 
295
  mesh_index_pair find_closest_circle_to_print(const float &X, const float &Y) {
296
    float closest = 99999.99;
297
    mesh_index_pair return_val;
298
 
299
    return_val.x_index = return_val.y_index = -1;
300
 
301
    for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
302
      for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
303
        if (!is_bitmap_set(circle_flags, i, j)) {
304
          const float mx = _GET_MESH_X(i),  // We found a circle that needs to be printed
305
                      my = _GET_MESH_Y(j);
306
 
307
          // Get the distance to this intersection
308
          float f = HYPOT(X - mx, Y - my);
309
 
310
          // It is possible that we are being called with the values
311
          // to let us find the closest circle to the start position.
312
          // But if this is not the case, add a small weighting to the
313
          // distance calculation to help it choose a better place to continue.
314
          f += HYPOT(g26_x_pos - mx, g26_y_pos - my) / 15.0;
315
 
316
          // Add in the specified amount of Random Noise to our search
317
          if (random_deviation > 1.0)
318
            f += random(0.0, random_deviation);
319
 
320
          if (f < closest) {
321
            closest = f;              // We found a closer location that is still
322
            return_val.x_index = i;   // un-printed  --- save the data for it
323
            return_val.y_index = j;
324
            return_val.distance = closest;
325
          }
326
        }
327
      }
328
    }
329
    bitmap_set(circle_flags, return_val.x_index, return_val.y_index);   // Mark this location as done.
330
    return return_val;
331
  }
332
 
333
  /**
334
   * print_line_from_here_to_there() takes two cartesian coordinates and draws a line from one
335
   * to the other. But there are really three sets of coordinates involved. The first coordinate
336
   * is the present location of the nozzle. We don't necessarily want to print from this location.
337
   * We first need to move the nozzle to the start of line segment where we want to print. Once
338
   * there, we can use the two coordinates supplied to draw the line.
339
   *
340
   * Note:  Although we assume the first set of coordinates is the start of the line and the second
341
   * set of coordinates is the end of the line, it does not always work out that way. This function
342
   * optimizes the movement to minimize the travel distance before it can start printing. This saves
343
   * a lot of time and eliminates a lot of nonsensical movement of the nozzle. However, it does
344
   * cause a lot of very little short retracement of th nozzle when it draws the very first line
345
   * segment of a 'circle'. The time this requires is very short and is easily saved by the other
346
   * cases where the optimization comes into play.
347
   */
348
  void print_line_from_here_to_there(const float &sx, const float &sy, const float &sz, const float &ex, const float &ey, const float &ez) {
349
    const float dx_s = current_position[X_AXIS] - sx,   // find our distance from the start of the actual line segment
350
                dy_s = current_position[Y_AXIS] - sy,
351
                dist_start = HYPOT2(dx_s, dy_s),        // We don't need to do a sqrt(), we can compare the distance^2
352
                                                        // to save computation time
353
                dx_e = current_position[X_AXIS] - ex,   // find our distance from the end of the actual line segment
354
                dy_e = current_position[Y_AXIS] - ey,
355
                dist_end = HYPOT2(dx_e, dy_e),
356
 
357
                line_length = HYPOT(ex - sx, ey - sy);
358
 
359
    // If the end point of the line is closer to the nozzle, flip the direction,
360
    // moving from the end to the start. On very small lines the optimization isn't worth it.
361
    if (dist_end < dist_start && (INTERSECTION_CIRCLE_RADIUS) < ABS(line_length))
362
      return print_line_from_here_to_there(ex, ey, ez, sx, sy, sz);
363
 
364
    // Decide whether to retract & bump
365
 
366
    if (dist_start > 2.0) {
367
      retract_filament(destination);
368
      //todo:  parameterize the bump height with a define
369
      move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + 0.500, 0.0);  // Z bump to minimize scraping
370
      move_to(sx, sy, sz + 0.500, 0.0); // Get to the starting point with no extrusion while bumped
371
    }
372
 
373
    move_to(sx, sy, sz, 0.0); // Get to the starting point with no extrusion / un-Z bump
374
 
375
    const float e_pos_delta = line_length * g26_e_axis_feedrate * g26_extrusion_multiplier;
376
 
377
    recover_filament(destination);
378
    move_to(ex, ey, ez, e_pos_delta);  // Get to the ending point with an appropriate amount of extrusion
379
  }
380
 
381
  inline bool look_for_lines_to_connect() {
382
    float sx, sy, ex, ey;
383
 
384
    for (uint8_t i = 0; i < GRID_MAX_POINTS_X; i++) {
385
      for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++) {
386
 
387
        #if ENABLED(ULTIPANEL)
388
          if (user_canceled()) return true;     // Check if the user wants to stop the Mesh Validation
389
        #endif
390
 
391
        if (i < GRID_MAX_POINTS_X) { // We can't connect to anything to the right than GRID_MAX_POINTS_X.
392
                                     // This is already a half circle because we are at the edge of the bed.
393
 
394
          if (is_bitmap_set(circle_flags, i, j) && is_bitmap_set(circle_flags, i + 1, j)) { // check if we can do a line to the left
395
            if (!is_bitmap_set(horizontal_mesh_line_flags, i, j)) {
396
 
397
              //
398
              // We found two circles that need a horizontal line to connect them
399
              // Print it!
400
              //
401
              sx = _GET_MESH_X(  i  ) + (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)); // right edge
402
              ex = _GET_MESH_X(i + 1) - (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)); // left edge
403
 
404
              sx = constrain(sx, X_MIN_POS + 1, X_MAX_POS - 1);
405
              sy = ey = constrain(_GET_MESH_Y(j), Y_MIN_POS + 1, Y_MAX_POS - 1);
406
              ex = constrain(ex, X_MIN_POS + 1, X_MAX_POS - 1);
407
 
408
              if (position_is_reachable(sx, sy) && position_is_reachable(ex, ey)) {
409
 
410
                if (g26_debug_flag) {
411
                  SERIAL_ECHOPAIR(" Connecting with horizontal line (sx=", sx);
412
                  SERIAL_ECHOPAIR(", sy=", sy);
413
                  SERIAL_ECHOPAIR(") -> (ex=", ex);
414
                  SERIAL_ECHOPAIR(", ey=", ey);
415
                  SERIAL_CHAR(')');
416
                  SERIAL_EOL();
417
                  //debug_current_and_destination(PSTR("Connecting horizontal line."));
418
                }
419
                print_line_from_here_to_there(sx, sy, g26_layer_height, ex, ey, g26_layer_height);
420
              }
421
              bitmap_set(horizontal_mesh_line_flags, i, j);   // Mark it as done so we don't do it again, even if we skipped it
422
            }
423
          }
424
 
425
          if (j < GRID_MAX_POINTS_Y) { // We can't connect to anything further back than GRID_MAX_POINTS_Y.
426
                                           // This is already a half circle because we are at the edge  of the bed.
427
 
428
            if (is_bitmap_set(circle_flags, i, j) && is_bitmap_set(circle_flags, i, j + 1)) { // check if we can do a line straight down
429
              if (!is_bitmap_set( vertical_mesh_line_flags, i, j)) {
430
                //
431
                // We found two circles that need a vertical line to connect them
432
                // Print it!
433
                //
434
                sy = _GET_MESH_Y(  j  ) + (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)); // top edge
435
                ey = _GET_MESH_Y(j + 1) - (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)); // bottom edge
436
 
437
                sx = ex = constrain(_GET_MESH_X(i), X_MIN_POS + 1, X_MAX_POS - 1);
438
                sy = constrain(sy, Y_MIN_POS + 1, Y_MAX_POS - 1);
439
                ey = constrain(ey, Y_MIN_POS + 1, Y_MAX_POS - 1);
440
 
441
                if (position_is_reachable(sx, sy) && position_is_reachable(ex, ey)) {
442
 
443
                  if (g26_debug_flag) {
444
                    SERIAL_ECHOPAIR(" Connecting with vertical line (sx=", sx);
445
                    SERIAL_ECHOPAIR(", sy=", sy);
446
                    SERIAL_ECHOPAIR(") -> (ex=", ex);
447
                    SERIAL_ECHOPAIR(", ey=", ey);
448
                    SERIAL_CHAR(')');
449
                    SERIAL_EOL();
450
 
451
                    #if ENABLED(AUTO_BED_LEVELING_UBL)
452
                      debug_current_and_destination(PSTR("Connecting vertical line."));
453
                    #endif
454
                  }
455
                  print_line_from_here_to_there(sx, sy, g26_layer_height, ex, ey, g26_layer_height);
456
                }
457
                bitmap_set(vertical_mesh_line_flags, i, j);   // Mark it as done so we don't do it again, even if skipped
458
              }
459
            }
460
          }
461
        }
462
      }
463
    }
464
    return false;
465
  }
466
 
467
  /**
468
   * Turn on the bed and nozzle heat and
469
   * wait for them to get up to temperature.
470
   */
471
  inline bool turn_on_heaters() {
472
    millis_t next = millis() + 5000UL;
473
    #if HAS_HEATED_BED
474
      #if ENABLED(ULTRA_LCD)
475
        if (g26_bed_temp > 25) {
476
          lcd_setstatusPGM(PSTR("G26 Heating Bed."), 99);
477
          lcd_quick_feedback(true);
478
          #if ENABLED(ULTIPANEL)
479
            lcd_external_control = true;
480
          #endif
481
      #endif
482
          thermalManager.setTargetBed(g26_bed_temp);
483
          while (ABS(thermalManager.degBed() - g26_bed_temp) > 3) {
484
 
485
            #if ENABLED(ULTIPANEL)
486
              if (is_lcd_clicked()) return exit_from_g26();
487
            #endif
488
 
489
            if (ELAPSED(millis(), next)) {
490
              next = millis() + 5000UL;
491
              thermalManager.print_heaterstates();
492
              SERIAL_EOL();
493
            }
494
            idle();
495
            SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
496
          }
497
      #if ENABLED(ULTRA_LCD)
498
        }
499
        lcd_setstatusPGM(PSTR("G26 Heating Nozzle."), 99);
500
        lcd_quick_feedback(true);
501
      #endif
502
    #endif
503
 
504
    // Start heating the nozzle and wait for it to reach temperature.
505
    thermalManager.setTargetHotend(g26_hotend_temp, 0);
506
    while (ABS(thermalManager.degHotend(0) - g26_hotend_temp) > 3) {
507
 
508
      #if ENABLED(ULTIPANEL)
509
        if (is_lcd_clicked()) return exit_from_g26();
510
      #endif
511
 
512
      if (ELAPSED(millis(), next)) {
513
        next = millis() + 5000UL;
514
        thermalManager.print_heaterstates();
515
        SERIAL_EOL();
516
      }
517
      idle();
518
 
519
      SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
520
    }
521
    #if ENABLED(ULTRA_LCD)
522
      lcd_reset_status();
523
      lcd_quick_feedback(true);
524
    #endif
525
 
526
    return G26_OK;
527
  }
528
 
529
  float valid_trig_angle(float d) {
530
    while (d > 360.0) d -= 360.0;
531
    while (d < 0.0) d += 360.0;
532
    return d;
533
  }
534
 
535
  /**
536
   * G26: Mesh Validation Pattern generation.
537
   *
538
   * Used to interactively edit the mesh by placing the
539
   * nozzle in a problem area and doing a G29 P4 R command.
540
   *
541
   * Parameters:
542
   *
543
   *  B  Bed Temperature
544
   *  C  Continue from the Closest mesh point
545
   *  D  Disable leveling before starting
546
   *  F  Filament diameter
547
   *  H  Hotend Temperature
548
   *  K  Keep heaters on when completed
549
   *  L  Layer Height
550
   *  O  Ooze extrusion length
551
   *  P  Prime length
552
   *  Q  Retraction multiplier
553
   *  R  Repetitions (number of grid points)
554
   *  S  Nozzle Size (diameter) in mm
555
   *  U  Random deviation (50 if no value given)
556
   *  X  X position
557
   *  Y  Y position
558
   */
559
  void gcode_G26() {
560
    SERIAL_ECHOLNPGM("G26 command started. Waiting for heater(s).");
561
 
562
    // Don't allow Mesh Validation without homing first,
563
    // or if the parameter parsing did not go OK, abort
564
    if (axis_unhomed_error()) return;
565
 
566
    g26_extrusion_multiplier    = EXTRUSION_MULTIPLIER;
567
    g26_retraction_multiplier   = RETRACTION_MULTIPLIER;
568
    g26_layer_height            = MESH_TEST_LAYER_HEIGHT;
569
    g26_prime_length            = PRIME_LENGTH;
570
    g26_bed_temp                = MESH_TEST_BED_TEMP;
571
    g26_hotend_temp             = MESH_TEST_HOTEND_TEMP;
572
    g26_prime_flag              = 0;
573
 
574
    float g26_nozzle            = MESH_TEST_NOZZLE_SIZE,
575
          g26_filament_diameter = DEFAULT_NOMINAL_FILAMENT_DIA,
576
          g26_ooze_amount       = parser.linearval('O', OOZE_AMOUNT);
577
 
578
    bool g26_continue_with_closest = parser.boolval('C'),
579
         g26_keep_heaters_on       = parser.boolval('K');
580
 
581
    if (parser.seenval('B')) {
582
      g26_bed_temp = parser.value_celsius();
583
      if (g26_bed_temp && !WITHIN(g26_bed_temp, 40, 140)) {
584
        SERIAL_PROTOCOLLNPGM("?Specified bed temperature not plausible (40-140C).");
585
        return;
586
      }
587
    }
588
 
589
    if (parser.seenval('L')) {
590
      g26_layer_height = parser.value_linear_units();
591
      if (!WITHIN(g26_layer_height, 0.0, 2.0)) {
592
        SERIAL_PROTOCOLLNPGM("?Specified layer height not plausible.");
593
        return;
594
      }
595
    }
596
 
597
    if (parser.seen('Q')) {
598
      if (parser.has_value()) {
599
        g26_retraction_multiplier = parser.value_float();
600
        if (!WITHIN(g26_retraction_multiplier, 0.05, 15.0)) {
601
          SERIAL_PROTOCOLLNPGM("?Specified Retraction Multiplier not plausible.");
602
          return;
603
        }
604
      }
605
      else {
606
        SERIAL_PROTOCOLLNPGM("?Retraction Multiplier must be specified.");
607
        return;
608
      }
609
    }
610
 
611
    if (parser.seenval('S')) {
612
      g26_nozzle = parser.value_float();
613
      if (!WITHIN(g26_nozzle, 0.1, 1.0)) {
614
        SERIAL_PROTOCOLLNPGM("?Specified nozzle size not plausible.");
615
        return;
616
      }
617
    }
618
 
619
    if (parser.seen('P')) {
620
      if (!parser.has_value()) {
621
        #if ENABLED(ULTIPANEL)
622
          g26_prime_flag = -1;
623
        #else
624
          SERIAL_PROTOCOLLNPGM("?Prime length must be specified when not using an LCD.");
625
          return;
626
        #endif
627
      }
628
      else {
629
        g26_prime_flag++;
630
        g26_prime_length = parser.value_linear_units();
631
        if (!WITHIN(g26_prime_length, 0.0, 25.0)) {
632
          SERIAL_PROTOCOLLNPGM("?Specified prime length not plausible.");
633
          return;
634
        }
635
      }
636
    }
637
 
638
    if (parser.seenval('F')) {
639
      g26_filament_diameter = parser.value_linear_units();
640
      if (!WITHIN(g26_filament_diameter, 1.0, 4.0)) {
641
        SERIAL_PROTOCOLLNPGM("?Specified filament size not plausible.");
642
        return;
643
      }
644
    }
645
    g26_extrusion_multiplier *= sq(1.75) / sq(g26_filament_diameter); // If we aren't using 1.75mm filament, we need to
646
                                                                      // scale up or down the length needed to get the
647
                                                                      // same volume of filament
648
 
649
    g26_extrusion_multiplier *= g26_filament_diameter * sq(g26_nozzle) / sq(0.3); // Scale up by nozzle size
650
 
651
    if (parser.seenval('H')) {
652
      g26_hotend_temp = parser.value_celsius();
653
      if (!WITHIN(g26_hotend_temp, 165, 280)) {
654
        SERIAL_PROTOCOLLNPGM("?Specified nozzle temperature not plausible.");
655
        return;
656
      }
657
    }
658
 
659
    if (parser.seen('U')) {
660
      randomSeed(millis());
661
      // This setting will persist for the next G26
662
      random_deviation = parser.has_value() ? parser.value_float() : 50.0;
663
    }
664
 
665
    int16_t g26_repeats;
666
    #if ENABLED(ULTIPANEL)
667
      g26_repeats = parser.intval('R', GRID_MAX_POINTS + 1);
668
    #else
669
      if (!parser.seen('R')) {
670
        SERIAL_PROTOCOLLNPGM("?(R)epeat must be specified when not using an LCD.");
671
        return;
672
      }
673
      else
674
        g26_repeats = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS + 1;
675
    #endif
676
    if (g26_repeats < 1) {
677
      SERIAL_PROTOCOLLNPGM("?(R)epeat value not plausible; must be at least 1.");
678
      return;
679
    }
680
 
681
    g26_x_pos = parser.seenval('X') ? RAW_X_POSITION(parser.value_linear_units()) : current_position[X_AXIS];
682
    g26_y_pos = parser.seenval('Y') ? RAW_Y_POSITION(parser.value_linear_units()) : current_position[Y_AXIS];
683
    if (!position_is_reachable(g26_x_pos, g26_y_pos)) {
684
      SERIAL_PROTOCOLLNPGM("?Specified X,Y coordinate out of bounds.");
685
      return;
686
    }
687
 
688
    /**
689
     * Wait until all parameters are verified before altering the state!
690
     */
691
    set_bed_leveling_enabled(!parser.seen('D'));
692
 
693
    if (current_position[Z_AXIS] < Z_CLEARANCE_BETWEEN_PROBES) {
694
      do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
695
      set_current_from_destination();
696
    }
697
 
698
    if (turn_on_heaters() != G26_OK) goto LEAVE;
699
 
700
    current_position[E_CART] = 0.0;
701
    sync_plan_position_e();
702
 
703
    if (g26_prime_flag && prime_nozzle() != G26_OK) goto LEAVE;
704
 
705
    /**
706
     *  Bed is preheated
707
     *
708
     *  Nozzle is at temperature
709
     *
710
     *  Filament is primed!
711
     *
712
     *  It's  "Show Time" !!!
713
     */
714
 
715
    ZERO(circle_flags);
716
    ZERO(horizontal_mesh_line_flags);
717
    ZERO(vertical_mesh_line_flags);
718
 
719
    // Move nozzle to the specified height for the first layer
720
    set_destination_from_current();
721
    destination[Z_AXIS] = g26_layer_height;
722
    move_to(destination, 0.0);
723
    move_to(destination, g26_ooze_amount);
724
 
725
    #if ENABLED(ULTIPANEL)
726
      lcd_external_control = true;
727
    #endif
728
 
729
    //debug_current_and_destination(PSTR("Starting G26 Mesh Validation Pattern."));
730
 
731
    #if DISABLED(ARC_SUPPORT)
732
 
733
      /**
734
       * Pre-generate radius offset values at 30 degree intervals to reduce CPU load.
735
       */
736
      #define A_INT 30
737
      #define _ANGS (360 / A_INT)
738
      #define A_CNT (_ANGS / 2)
739
      #define _IND(A) ((A + _ANGS * 8) % _ANGS)
740
      #define _COS(A) (trig_table[_IND(A) % A_CNT] * (_IND(A) >= A_CNT ? -1 : 1))
741
      #define _SIN(A) (-_COS((A + A_CNT / 2) % _ANGS))
742
      #if A_CNT & 1
743
        #error "A_CNT must be a positive value. Please change A_INT."
744
      #endif
745
      float trig_table[A_CNT];
746
      for (uint8_t i = 0; i < A_CNT; i++)
747
        trig_table[i] = INTERSECTION_CIRCLE_RADIUS * cos(RADIANS(i * A_INT));
748
 
749
    #endif // !ARC_SUPPORT
750
 
751
    mesh_index_pair location;
752
    do {
753
       location = g26_continue_with_closest
754
        ? find_closest_circle_to_print(current_position[X_AXIS], current_position[Y_AXIS])
755
        : find_closest_circle_to_print(g26_x_pos, g26_y_pos); // Find the closest Mesh Intersection to where we are now.
756
 
757
      if (location.x_index >= 0 && location.y_index >= 0) {
758
        const float circle_x = _GET_MESH_X(location.x_index),
759
                    circle_y = _GET_MESH_Y(location.y_index);
760
 
761
        // If this mesh location is outside the printable_radius, skip it.
762
        if (!position_is_reachable(circle_x, circle_y)) continue;
763
 
764
        // Determine where to start and end the circle,
765
        // which is always drawn counter-clockwise.
766
        const uint8_t xi = location.x_index, yi = location.y_index;
767
        const bool f = yi == 0, r = xi >= GRID_MAX_POINTS_X - 1, b = yi >= GRID_MAX_POINTS_Y - 1;
768
 
769
        #if ENABLED(ARC_SUPPORT)
770
 
771
          #define ARC_LENGTH(quarters)  (INTERSECTION_CIRCLE_RADIUS * M_PI * (quarters) / 2)
772
          float sx = circle_x + INTERSECTION_CIRCLE_RADIUS,   // default to full circle
773
                ex = circle_x + INTERSECTION_CIRCLE_RADIUS,
774
                sy = circle_y, ey = circle_y,
775
                arc_length = ARC_LENGTH(4);
776
 
777
          // Figure out where to start and end the arc - we always print counterclockwise
778
          if (xi == 0) {                             // left edge
779
            sx = f ? circle_x + INTERSECTION_CIRCLE_RADIUS : circle_x;
780
            ex = b ? circle_x + INTERSECTION_CIRCLE_RADIUS : circle_x;
781
            sy = f ? circle_y : circle_y - INTERSECTION_CIRCLE_RADIUS;
782
            ey = b ? circle_y : circle_y + INTERSECTION_CIRCLE_RADIUS;
783
            arc_length = (f || b) ? ARC_LENGTH(1) : ARC_LENGTH(2);
784
          }
785
          else if (r) {                             // right edge
786
            sx = b ? circle_x - INTERSECTION_CIRCLE_RADIUS : circle_x;
787
            ex = f ? circle_x - INTERSECTION_CIRCLE_RADIUS : circle_x;
788
            sy = b ? circle_y : circle_y + INTERSECTION_CIRCLE_RADIUS;
789
            ey = f ? circle_y : circle_y - INTERSECTION_CIRCLE_RADIUS;
790
            arc_length = (f || b) ? ARC_LENGTH(1) : ARC_LENGTH(2);
791
          }
792
          else if (f) {
793
            sx = circle_x + INTERSECTION_CIRCLE_RADIUS;
794
            ex = circle_x - INTERSECTION_CIRCLE_RADIUS;
795
            sy = ey = circle_y;
796
            arc_length = ARC_LENGTH(2);
797
          }
798
          else if (b) {
799
            sx = circle_x - INTERSECTION_CIRCLE_RADIUS;
800
            ex = circle_x + INTERSECTION_CIRCLE_RADIUS;
801
            sy = ey = circle_y;
802
            arc_length = ARC_LENGTH(2);
803
          }
804
          const float arc_offset[2] = {
805
            circle_x - sx,
806
            circle_y - sy
807
          };
808
 
809
          const float dx_s = current_position[X_AXIS] - sx,   // find our distance from the start of the actual circle
810
                      dy_s = current_position[Y_AXIS] - sy,
811
                      dist_start = HYPOT2(dx_s, dy_s);
812
          const float endpoint[XYZE] = {
813
            ex, ey,
814
            g26_layer_height,
815
            current_position[E_CART] + (arc_length * g26_e_axis_feedrate * g26_extrusion_multiplier)
816
          };
817
 
818
          if (dist_start > 2.0) {
819
            retract_filament(destination);
820
            //todo:  parameterize the bump height with a define
821
            move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + 0.500, 0.0);  // Z bump to minimize scraping
822
            move_to(sx, sy, g26_layer_height + 0.500, 0.0); // Get to the starting point with no extrusion while bumped
823
          }
824
 
825
          move_to(sx, sy, g26_layer_height, 0.0); // Get to the starting point with no extrusion / un-Z bump
826
 
827
          recover_filament(destination);
828
          const float save_feedrate = feedrate_mm_s;
829
          feedrate_mm_s = PLANNER_XY_FEEDRATE() / 10.0;
830
          plan_arc(endpoint, arc_offset, false);  // Draw a counter-clockwise arc
831
          feedrate_mm_s = save_feedrate;
832
          set_destination_from_current();
833
          #if ENABLED(ULTIPANEL)
834
            if (user_canceled()) goto LEAVE; // Check if the user wants to stop the Mesh Validation
835
          #endif
836
 
837
        #else // !ARC_SUPPORT
838
 
839
          int8_t start_ind = -2, end_ind = 9; // Assume a full circle (from 5:00 to 5:00)
840
          if (xi == 0) {                      // Left edge? Just right half.
841
            start_ind = f ? 0 : -3;           //  03:00 to 12:00 for front-left
842
            end_ind = b ? 0 : 2;              //  06:00 to 03:00 for back-left
843
          }
844
          else if (r) {                       // Right edge? Just left half.
845
            start_ind = b ? 6 : 3;            //  12:00 to 09:00 for front-right
846
            end_ind = f ? 5 : 8;              //  09:00 to 06:00 for back-right
847
          }
848
          else if (f) {                       // Front edge? Just back half.
849
            start_ind = 0;                    //  03:00
850
            end_ind = 5;                      //  09:00
851
          }
852
          else if (b) {                       // Back edge? Just front half.
853
            start_ind = 6;                    //  09:00
854
            end_ind = 11;                     //  03:00
855
          }
856
 
857
          for (int8_t ind = start_ind; ind <= end_ind; ind++) {
858
 
859
            #if ENABLED(ULTIPANEL)
860
              if (user_canceled()) goto LEAVE;          // Check if the user wants to stop the Mesh Validation
861
            #endif
862
 
863
            float rx = circle_x + _COS(ind),            // For speed, these are now a lookup table entry
864
                  ry = circle_y + _SIN(ind),
865
                  xe = circle_x + _COS(ind + 1),
866
                  ye = circle_y + _SIN(ind + 1);
867
 
868
            #if IS_KINEMATIC
869
              // Check to make sure this segment is entirely on the bed, skip if not.
870
              if (!position_is_reachable(rx, ry) || !position_is_reachable(xe, ye)) continue;
871
            #else                                               // not, we need to skip
872
              rx = constrain(rx, X_MIN_POS + 1, X_MAX_POS - 1); // This keeps us from bumping the endstops
873
              ry = constrain(ry, Y_MIN_POS + 1, Y_MAX_POS - 1);
874
              xe = constrain(xe, X_MIN_POS + 1, X_MAX_POS - 1);
875
              ye = constrain(ye, Y_MIN_POS + 1, Y_MAX_POS - 1);
876
            #endif
877
 
878
            print_line_from_here_to_there(rx, ry, g26_layer_height, xe, ye, g26_layer_height);
879
            SERIAL_FLUSH();  // Prevent host M105 buffer overrun.
880
          }
881
 
882
        #endif // !ARC_SUPPORT
883
 
884
        if (look_for_lines_to_connect()) goto LEAVE;
885
      }
886
 
887
      SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
888
 
889
    } while (--g26_repeats && location.x_index >= 0 && location.y_index >= 0);
890
 
891
    LEAVE:
892
    lcd_setstatusPGM(PSTR("Leaving G26"), -1);
893
 
894
    retract_filament(destination);
895
    destination[Z_AXIS] = Z_CLEARANCE_BETWEEN_PROBES;
896
 
897
    //debug_current_and_destination(PSTR("ready to do Z-Raise."));
898
    move_to(destination, 0); // Raise the nozzle
899
    //debug_current_and_destination(PSTR("done doing Z-Raise."));
900
 
901
    destination[X_AXIS] = g26_x_pos;                               // Move back to the starting position
902
    destination[Y_AXIS] = g26_y_pos;
903
    //destination[Z_AXIS] = Z_CLEARANCE_BETWEEN_PROBES;            // Keep the nozzle where it is
904
 
905
    move_to(destination, 0); // Move back to the starting position
906
    //debug_current_and_destination(PSTR("done doing X/Y move."));
907
 
908
    #if ENABLED(ULTIPANEL)
909
      lcd_external_control = false;     // Give back control of the LCD Panel!
910
    #endif
911
 
912
    if (!g26_keep_heaters_on) {
913
      #if HAS_HEATED_BED
914
        thermalManager.setTargetBed(0);
915
      #endif
916
      thermalManager.setTargetHotend(0, 0);
917
    }
918
  }
919
 
920
#endif // G26_MESH_VALIDATION