planner.cpp

changeset 0
2c8ba1964db7
child 1
b584642d4f58
equal deleted inserted replaced
-1:000000000000 0:2c8ba1964db7
1 /*
2 planner.c - buffers movement commands and manages the acceleration profile plan
3 Part of Grbl
4
5 Copyright (c) 2009-2011 Simen Svale Skogsrud
6
7 Grbl is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 Grbl is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Grbl. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /* The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis. */
22
23 /*
24 Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
25
26 s == speed, a == acceleration, t == time, d == distance
27
28 Basic definitions:
29
30 Speed[s_, a_, t_] := s + (a*t)
31 Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
32
33 Distance to reach a specific speed with a constant acceleration:
34
35 Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
36 d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
37
38 Speed after a given distance of travel with constant acceleration:
39
40 Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
41 m -> Sqrt[2 a d + s^2]
42
43 DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
44
45 When to start braking (di) to reach a specified destionation speed (s2) after accelerating
46 from initial speed s1 without ever stopping at a plateau:
47
48 Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
49 di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
50
51 IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
52 */
53
54 #include "Marlin.h"
55 #include "planner.h"
56 #include "stepper.h"
57 #include "temperature.h"
58 #include "ultralcd.h"
59 #include "language.h"
60 #include "led.h"
61
62 //===========================================================================
63 //=============================public variables ============================
64 //===========================================================================
65
66 unsigned long minsegmenttime;
67 float max_feedrate[4]; // set the max speeds
68 float axis_steps_per_unit[4];
69 unsigned long max_acceleration_units_per_sq_second[4]; // Use M201 to override by software
70 float minimumfeedrate;
71 float acceleration; // Normal acceleration mm/s^2 THIS IS THE DEFAULT ACCELERATION for all moves. M204 SXXXX
72 float retract_acceleration; // mm/s^2 filament pull-pack and push-forward while standing still in the other axis M204 TXXXX
73 float max_xy_jerk; //speed than can be stopped at once, if i understand correctly.
74 float max_z_jerk;
75 float max_e_jerk;
76 float mintravelfeedrate;
77 unsigned long axis_steps_per_sqr_second[NUM_AXIS];
78
79 // The current position of the tool in absolute steps
80 long position[4]; //rescaled from extern when axis_steps_per_unit are changed by gcode
81 static float previous_speed[4]; // Speed of previous path line segment
82 static float previous_nominal_speed; // Nominal speed of previous path line segment
83
84 extern volatile int extrudemultiply; // Sets extrude multiply factor (in percent)
85
86 #ifdef AUTOTEMP
87 float autotemp_max=250;
88 float autotemp_min=210;
89 float autotemp_factor=0.1;
90 bool autotemp_enabled=false;
91 #endif
92
93 //===========================================================================
94 //=================semi-private variables, used in inline functions =====
95 //===========================================================================
96 block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instfructions
97 volatile unsigned char block_buffer_head; // Index of the next block to be pushed
98 volatile unsigned char block_buffer_tail; // Index of the block to process now
99
100 //===========================================================================
101 //=============================private variables ============================
102 //===========================================================================
103 #ifdef PREVENT_DANGEROUS_EXTRUDE
104 bool allow_cold_extrude=false;
105 #endif
106 #ifdef XY_FREQUENCY_LIMIT
107 // Used for the frequency limit
108 static unsigned char old_direction_bits = 0; // Old direction bits. Used for speed calculations
109 static long x_segment_time[3]={0,0,0}; // Segment times (in us). Used for speed calculations
110 static long y_segment_time[3]={0,0,0};
111 #endif
112
113 // Returns the index of the next block in the ring buffer
114 // NOTE: Removed modulo (%) operator, which uses an expensive divide and multiplication.
115 static int8_t next_block_index(int8_t block_index) {
116 block_index++;
117 if (block_index == BLOCK_BUFFER_SIZE) { block_index = 0; }
118 return(block_index);
119 }
120
121
122 // Returns the index of the previous block in the ring buffer
123 static int8_t prev_block_index(int8_t block_index) {
124 if (block_index == 0) { block_index = BLOCK_BUFFER_SIZE; }
125 block_index--;
126 return(block_index);
127 }
128
129 //===========================================================================
130 //=============================functions ============================
131 //===========================================================================
132
133 // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the
134 // given acceleration:
135 FORCE_INLINE float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration)
136 {
137 if (acceleration!=0) {
138 return((target_rate*target_rate-initial_rate*initial_rate)/
139 (2.0*acceleration));
140 }
141 else {
142 return 0.0; // acceleration was 0, set acceleration distance to 0
143 }
144 }
145
146 // This function gives you the point at which you must start braking (at the rate of -acceleration) if
147 // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after
148 // a total travel of distance. This can be used to compute the intersection point between acceleration and
149 // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed)
150
151 FORCE_INLINE float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance)
152 {
153 if (acceleration!=0) {
154 return((2.0*acceleration*distance-initial_rate*initial_rate+final_rate*final_rate)/
155 (4.0*acceleration) );
156 }
157 else {
158 return 0.0; // acceleration was 0, set intersection distance to 0
159 }
160 }
161
162 // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors.
163
164 void calculate_trapezoid_for_block(block_t *block, float entry_factor, float exit_factor) {
165 unsigned long initial_rate = ceil(block->nominal_rate*entry_factor); // (step/min)
166 unsigned long final_rate = ceil(block->nominal_rate*exit_factor); // (step/min)
167
168 // Limit minimal step rate (Otherwise the timer will overflow.)
169 if(initial_rate <120) {initial_rate=120; }
170 if(final_rate < 120) {final_rate=120; }
171
172 long acceleration = block->acceleration_st;
173 int32_t accelerate_steps =
174 ceil(estimate_acceleration_distance(block->initial_rate, block->nominal_rate, acceleration));
175 int32_t decelerate_steps =
176 floor(estimate_acceleration_distance(block->nominal_rate, block->final_rate, -acceleration));
177
178 // Calculate the size of Plateau of Nominal Rate.
179 int32_t plateau_steps = block->step_event_count-accelerate_steps-decelerate_steps;
180
181 // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
182 // have to use intersection_distance() to calculate when to abort acceleration and start braking
183 // in order to reach the final_rate exactly at the end of this block.
184 if (plateau_steps < 0) {
185 accelerate_steps = ceil(
186 intersection_distance(block->initial_rate, block->final_rate, acceleration, block->step_event_count));
187 accelerate_steps = max(accelerate_steps,0); // Check limits due to numerical round-off
188 accelerate_steps = min(accelerate_steps,block->step_event_count);
189 plateau_steps = 0;
190 }
191
192 #ifdef ADVANCE
193 volatile long initial_advance = block->advance*entry_factor*entry_factor;
194 volatile long final_advance = block->advance*exit_factor*exit_factor;
195 #endif // ADVANCE
196
197 // block->accelerate_until = accelerate_steps;
198 // block->decelerate_after = accelerate_steps+plateau_steps;
199 CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
200 if(block->busy == false) { // Don't update variables if block is busy.
201 block->accelerate_until = accelerate_steps;
202 block->decelerate_after = accelerate_steps+plateau_steps;
203 block->initial_rate = initial_rate;
204 block->final_rate = final_rate;
205 #ifdef ADVANCE
206 block->initial_advance = initial_advance;
207 block->final_advance = final_advance;
208 #endif //ADVANCE
209 }
210 CRITICAL_SECTION_END;
211 }
212
213 // Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the
214 // acceleration within the allotted distance.
215 FORCE_INLINE float max_allowable_speed(float acceleration, float target_velocity, float distance) {
216 return sqrt(target_velocity*target_velocity-2*acceleration*distance);
217 }
218
219 // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
220 // This method will calculate the junction jerk as the euclidean distance between the nominal
221 // velocities of the respective blocks.
222 //inline float junction_jerk(block_t *before, block_t *after) {
223 // return sqrt(
224 // pow((before->speed_x-after->speed_x), 2)+pow((before->speed_y-after->speed_y), 2));
225 //}
226
227
228 // The kernel called by planner_recalculate() when scanning the plan from last to first entry.
229 void planner_reverse_pass_kernel(block_t *previous, block_t *current, block_t *next) {
230 if(!current) { return; }
231
232 if (next) {
233 // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
234 // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
235 // check for maximum allowable speed reductions to ensure maximum possible planned speed.
236 if (current->entry_speed != current->max_entry_speed) {
237
238 // If nominal length true, max junction speed is guaranteed to be reached. Only compute
239 // for max allowable speed if block is decelerating and nominal length is false.
240 if ((!current->nominal_length_flag) && (current->max_entry_speed > next->entry_speed)) {
241 current->entry_speed = min( current->max_entry_speed,
242 max_allowable_speed(-current->acceleration,next->entry_speed,current->millimeters));
243 } else {
244 current->entry_speed = current->max_entry_speed;
245 }
246 current->recalculate_flag = true;
247
248 }
249 } // Skip last block. Already initialized and set for recalculation.
250 }
251
252 // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This
253 // implements the reverse pass.
254 void planner_reverse_pass() {
255 uint8_t block_index = block_buffer_head;
256 if(((block_buffer_head-block_buffer_tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1)) > 3) {
257 block_index = (block_buffer_head - 3) & (BLOCK_BUFFER_SIZE - 1);
258 block_t *block[3] = { NULL, NULL, NULL };
259 while(block_index != block_buffer_tail) {
260 block_index = prev_block_index(block_index);
261 block[2]= block[1];
262 block[1]= block[0];
263 block[0] = &block_buffer[block_index];
264 planner_reverse_pass_kernel(block[0], block[1], block[2]);
265 }
266 }
267 }
268
269 // The kernel called by planner_recalculate() when scanning the plan from first to last entry.
270 void planner_forward_pass_kernel(block_t *previous, block_t *current, block_t *next) {
271 if(!previous) { return; }
272
273 // If the previous block is an acceleration block, but it is not long enough to complete the
274 // full speed change within the block, we need to adjust the entry speed accordingly. Entry
275 // speeds have already been reset, maximized, and reverse planned by reverse planner.
276 // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
277 if (!previous->nominal_length_flag) {
278 if (previous->entry_speed < current->entry_speed) {
279 double entry_speed = min( current->entry_speed,
280 max_allowable_speed(-previous->acceleration,previous->entry_speed,previous->millimeters) );
281
282 // Check for junction speed change
283 if (current->entry_speed != entry_speed) {
284 current->entry_speed = entry_speed;
285 current->recalculate_flag = true;
286 }
287 }
288 }
289 }
290
291 // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This
292 // implements the forward pass.
293 void planner_forward_pass() {
294 uint8_t block_index = block_buffer_tail;
295 block_t *block[3] = { NULL, NULL, NULL };
296
297 while(block_index != block_buffer_head) {
298 block[0] = block[1];
299 block[1] = block[2];
300 block[2] = &block_buffer[block_index];
301 planner_forward_pass_kernel(block[0],block[1],block[2]);
302 block_index = next_block_index(block_index);
303 }
304 planner_forward_pass_kernel(block[1], block[2], NULL);
305 }
306
307 // Recalculates the trapezoid speed profiles for all blocks in the plan according to the
308 // entry_factor for each junction. Must be called by planner_recalculate() after
309 // updating the blocks.
310 void planner_recalculate_trapezoids() {
311 int8_t block_index = block_buffer_tail;
312 block_t *current;
313 block_t *next = NULL;
314
315 while(block_index != block_buffer_head) {
316 current = next;
317 next = &block_buffer[block_index];
318 if (current) {
319 // Recalculate if current block entry or exit junction speed has changed.
320 if (current->recalculate_flag || next->recalculate_flag) {
321 // NOTE: Entry and exit factors always > 0 by all previous logic operations.
322 calculate_trapezoid_for_block(current, current->entry_speed/current->nominal_speed,
323 next->entry_speed/current->nominal_speed);
324 current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed
325 }
326 }
327 block_index = next_block_index( block_index );
328 }
329 // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
330 if(next != NULL) {
331 calculate_trapezoid_for_block(next, next->entry_speed/next->nominal_speed,
332 MINIMUM_PLANNER_SPEED/next->nominal_speed);
333 next->recalculate_flag = false;
334 }
335 }
336
337 // Recalculates the motion plan according to the following algorithm:
338 //
339 // 1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_factor)
340 // so that:
341 // a. The junction jerk is within the set limit
342 // b. No speed reduction within one block requires faster deceleration than the one, true constant
343 // acceleration.
344 // 2. Go over every block in chronological order and dial down junction speed reduction values if
345 // a. The speed increase within one block would require faster accelleration than the one, true
346 // constant acceleration.
347 //
348 // When these stages are complete all blocks have an entry_factor that will allow all speed changes to
349 // be performed using only the one, true constant acceleration, and where no junction jerk is jerkier than
350 // the set limit. Finally it will:
351 //
352 // 3. Recalculate trapezoids for all blocks.
353
354 void planner_recalculate() {
355 planner_reverse_pass();
356 planner_forward_pass();
357 planner_recalculate_trapezoids();
358 }
359
360 void plan_init() {
361 block_buffer_head = 0;
362 block_buffer_tail = 0;
363 memset(position, 0, sizeof(position)); // clear position
364 previous_speed[0] = 0.0;
365 previous_speed[1] = 0.0;
366 previous_speed[2] = 0.0;
367 previous_speed[3] = 0.0;
368 previous_nominal_speed = 0.0;
369 }
370
371
372
373
374 #ifdef AUTOTEMP
375 void getHighESpeed()
376 {
377 static float oldt=0;
378 if(!autotemp_enabled){
379 return;
380 }
381 if(degTargetHotend0()+2<autotemp_min) { //probably temperature set to zero.
382 return; //do nothing
383 }
384
385 float high=0.0;
386 uint8_t block_index = block_buffer_tail;
387
388 while(block_index != block_buffer_head) {
389 if((block_buffer[block_index].steps_x != 0) ||
390 (block_buffer[block_index].steps_y != 0) ||
391 (block_buffer[block_index].steps_z != 0)) {
392 float se=(float(block_buffer[block_index].steps_e)/float(block_buffer[block_index].step_event_count))*block_buffer[block_index].nominal_speed;
393 //se; mm/sec;
394 if(se>high)
395 {
396 high=se;
397 }
398 }
399 block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
400 }
401
402 float g=autotemp_min+high*autotemp_factor;
403 float t=g;
404 if(t<autotemp_min)
405 t=autotemp_min;
406 if(t>autotemp_max)
407 t=autotemp_max;
408 if(oldt>t)
409 {
410 t=AUTOTEMP_OLDWEIGHT*oldt+(1-AUTOTEMP_OLDWEIGHT)*t;
411 }
412 oldt=t;
413 setTargetHotend0(t);
414 }
415 #endif
416
417 void check_axes_activity() {
418 unsigned char x_active = 0;
419 unsigned char y_active = 0;
420 unsigned char z_active = 0;
421 unsigned char e_active = 0;
422 unsigned char fan_speed = 0;
423 unsigned char tail_fan_speed = 0;
424 block_t *block;
425
426 if(block_buffer_tail != block_buffer_head) {
427 uint8_t block_index = block_buffer_tail;
428 tail_fan_speed = block_buffer[block_index].fan_speed;
429 while(block_index != block_buffer_head) {
430 block = &block_buffer[block_index];
431 if(block->steps_x != 0) x_active++;
432 if(block->steps_y != 0) y_active++;
433 if(block->steps_z != 0) z_active++;
434 if(block->steps_e != 0) e_active++;
435 if(block->fan_speed != 0) fan_speed++;
436 block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
437 }
438 }
439 else {
440 #if FAN_PIN > -1
441 if (FanSpeed != 0) analogWrite(FAN_PIN,FanSpeed); // If buffer is empty use current fan speed
442 #endif
443 }
444 if((DISABLE_X) && (x_active == 0)) disable_x();
445 if((DISABLE_Y) && (y_active == 0)) disable_y();
446 if((DISABLE_Z) && (z_active == 0)) disable_z();
447 if((DISABLE_E) && (e_active == 0)) { disable_e0();disable_e1();disable_e2(); }
448 #if FAN_PIN > -1
449 if((FanSpeed == 0) && (fan_speed ==0)) analogWrite(FAN_PIN, 0);
450 #endif
451 if (FanSpeed != 0 && tail_fan_speed !=0) {
452 analogWrite(FAN_PIN,tail_fan_speed);
453 }
454 }
455
456
457 float junction_deviation = 0.1;
458 // Add a new linear movement to the buffer. steps_x, _y and _z is the absolute position in
459 // mm. Microseconds specify how many microseconds the move should take to perform. To aid acceleration
460 // calculation the caller must also provide the physical length of the line in millimeters.
461 void plan_buffer_line(const float &x, const float &y, const float &z, const float &e, float feed_rate, const uint8_t &extruder)
462 {
463 // Calculate the buffer head after we push this byte
464 int next_buffer_head = next_block_index(block_buffer_head);
465
466 // If the buffer is full: good! That means we are well ahead of the robot.
467 // Rest here until there is room in the buffer.
468 while(block_buffer_tail == next_buffer_head) {
469 manage_heater();
470 manage_inactivity(1);
471 LCD_STATUS;
472 LED_STATUS;
473 }
474
475 // The target position of the tool in absolute steps
476 // Calculate target position in absolute steps
477 //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
478 long target[4];
479 target[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
480 target[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
481 target[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
482 target[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
483
484 #ifdef PREVENT_DANGEROUS_EXTRUDE
485 if(target[E_AXIS]!=position[E_AXIS])
486 if(degHotend(active_extruder)<EXTRUDE_MINTEMP && !allow_cold_extrude)
487 {
488 position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
489 SERIAL_ECHO_START;
490 SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
491 }
492 if(labs(target[E_AXIS]-position[E_AXIS])>axis_steps_per_unit[E_AXIS]*EXTRUDE_MAXLENGTH)
493 {
494 position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
495 SERIAL_ECHO_START;
496 SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
497 }
498 #endif
499
500 // Prepare to set up new block
501 block_t *block = &block_buffer[block_buffer_head];
502
503 // Mark block as not busy (Not executed by the stepper interrupt)
504 block->busy = false;
505
506 // Number of steps for each axis
507 block->steps_x = labs(target[X_AXIS]-position[X_AXIS]);
508 block->steps_y = labs(target[Y_AXIS]-position[Y_AXIS]);
509 block->steps_z = labs(target[Z_AXIS]-position[Z_AXIS]);
510 block->steps_e = labs(target[E_AXIS]-position[E_AXIS]);
511 block->steps_e *= extrudemultiply;
512 block->steps_e /= 100;
513 block->step_event_count = max(block->steps_x, max(block->steps_y, max(block->steps_z, block->steps_e)));
514
515 // Bail if this is a zero-length block
516 if (block->step_event_count <= dropsegments) { return; };
517
518 block->fan_speed = FanSpeed;
519
520 // Compute direction bits for this block
521 block->direction_bits = 0;
522 if (target[X_AXIS] < position[X_AXIS]) { block->direction_bits |= (1<<X_AXIS); }
523 if (target[Y_AXIS] < position[Y_AXIS]) { block->direction_bits |= (1<<Y_AXIS); }
524 if (target[Z_AXIS] < position[Z_AXIS]) { block->direction_bits |= (1<<Z_AXIS); }
525 if (target[E_AXIS] < position[E_AXIS]) { block->direction_bits |= (1<<E_AXIS); }
526
527 block->active_extruder = extruder;
528
529 //enable active axes
530 if(block->steps_x != 0) enable_x();
531 if(block->steps_y != 0) enable_y();
532 #ifndef Z_LATE_ENABLE
533 if(block->steps_z != 0) enable_z();
534 #endif
535
536 // Enable all
537 // N571 disables real E drive! (ie. on laser operations)
538 if (!n571_enabled) {
539 if(block->steps_e != 0) { enable_e0();enable_e1();enable_e2(); }
540 }
541
542 if (block->steps_e == 0) {
543 if(feed_rate<mintravelfeedrate) feed_rate=mintravelfeedrate;
544 }
545 else {
546 if(feed_rate<minimumfeedrate) feed_rate=minimumfeedrate;
547 }
548
549 float delta_mm[4];
550 delta_mm[X_AXIS] = (target[X_AXIS]-position[X_AXIS])/axis_steps_per_unit[X_AXIS];
551 delta_mm[Y_AXIS] = (target[Y_AXIS]-position[Y_AXIS])/axis_steps_per_unit[Y_AXIS];
552 delta_mm[Z_AXIS] = (target[Z_AXIS]-position[Z_AXIS])/axis_steps_per_unit[Z_AXIS];
553 delta_mm[E_AXIS] = ((target[E_AXIS]-position[E_AXIS])/axis_steps_per_unit[E_AXIS])*extrudemultiply/100.0;
554 // if ( block->steps_x <=dropsegments && block->steps_y <=dropsegments && block->steps_z <=dropsegments ) {
555 // block->millimeters = abs(delta_mm[E_AXIS]);
556 // } else {
557 // block->millimeters = sqrt(square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_AXIS]));
558 // }
559
560 // TODO - JMG - SORT OUT RETRACTS WHEN e IS NOT ALONE
561 block->millimeters = sqrt(square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) +
562 square(delta_mm[Z_AXIS]) + square(delta_mm[E_AXIS]));
563 float inverse_millimeters = 1.0/block->millimeters; // Inverse millimeters to remove multiple divides
564
565 // Calculate speed in mm/second for each axis. No divide by zero due to previous checks.
566 float inverse_second = feed_rate * inverse_millimeters;
567
568 int moves_queued=(block_buffer_head-block_buffer_tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1);
569
570 // slow down when de buffer starts to empty, rather than wait at the corner for a buffer refill
571 #ifdef OLD_SLOWDOWN
572 if(moves_queued < (BLOCK_BUFFER_SIZE * 0.5) && moves_queued > 1) feed_rate = feed_rate*moves_queued / (BLOCK_BUFFER_SIZE * 0.5);
573 #endif
574
575 #ifdef SLOWDOWN
576 // segment time im micro seconds
577 unsigned long segment_time = lround(1000000.0/inverse_second);
578 if ((moves_queued > 1) && (moves_queued < (BLOCK_BUFFER_SIZE * 0.5))) {
579 if (segment_time < minsegmenttime) { // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
580 inverse_second=1000000.0/(segment_time+lround(2*(minsegmenttime-segment_time)/moves_queued));
581 }
582 }
583 #endif
584 // END OF SLOW DOWN SECTION
585
586
587 block->nominal_speed = block->millimeters * inverse_second; // (mm/sec) Always > 0
588 block->nominal_rate = ceil(block->step_event_count * inverse_second); // (step/sec) Always > 0
589
590 // Calculate and limit speed in mm/sec for each axis
591 float current_speed[4];
592 float speed_factor = 1.0; //factor <=1 do decrease speed
593 for(int i=0; i < 4; i++) {
594 current_speed[i] = delta_mm[i] * inverse_second;
595 if(fabs(current_speed[i]) > max_feedrate[i])
596 speed_factor = min(speed_factor, max_feedrate[i] / fabs(current_speed[i]));
597 }
598
599 // Max segement time in us.
600 #ifdef XY_FREQUENCY_LIMIT
601 #define MAX_FREQ_TIME (1000000.0/XY_FREQUENCY_LIMIT)
602
603 // Check and limit the xy direction change frequency
604 unsigned char direction_change = block->direction_bits ^ old_direction_bits;
605 old_direction_bits = block->direction_bits;
606
607 if((direction_change & (1<<X_AXIS)) == 0) {
608 x_segment_time[0] += segment_time;
609 }
610 else {
611 x_segment_time[2] = x_segment_time[1];
612 x_segment_time[1] = x_segment_time[0];
613 x_segment_time[0] = segment_time;
614 }
615 if((direction_change & (1<<Y_AXIS)) == 0) {
616 y_segment_time[0] += segment_time;
617 }
618 else {
619 y_segment_time[2] = y_segment_time[1];
620 y_segment_time[1] = y_segment_time[0];
621 y_segment_time[0] = segment_time;
622 }
623 long max_x_segment_time = max(x_segment_time[0], max(x_segment_time[1], x_segment_time[2]));
624 long max_y_segment_time = max(y_segment_time[0], max(y_segment_time[1], y_segment_time[2]));
625 long min_xy_segment_time =min(max_x_segment_time, max_y_segment_time);
626 if(min_xy_segment_time < MAX_FREQ_TIME) speed_factor = min(speed_factor, speed_factor * (float)min_xy_segment_time / (float)MAX_FREQ_TIME);
627 #endif
628
629 // Correct the speed
630 if( speed_factor < 1.0) {
631 for(unsigned char i=0; i < 4; i++) {
632 current_speed[i] *= speed_factor;
633 }
634 block->nominal_speed *= speed_factor;
635 block->nominal_rate *= speed_factor;
636 }
637
638 // Compute and limit the acceleration rate for the trapezoid generator.
639 float steps_per_mm = block->step_event_count/block->millimeters;
640 if(block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0) {
641 block->acceleration_st = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
642 }
643 else {
644 block->acceleration_st = ceil(acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
645 // Limit acceleration per axis
646 if(((float)block->acceleration_st * (float)block->steps_x / (float)block->step_event_count) > axis_steps_per_sqr_second[X_AXIS])
647 block->acceleration_st = axis_steps_per_sqr_second[X_AXIS];
648 if(((float)block->acceleration_st * (float)block->steps_y / (float)block->step_event_count) > axis_steps_per_sqr_second[Y_AXIS])
649 block->acceleration_st = axis_steps_per_sqr_second[Y_AXIS];
650 if(((float)block->acceleration_st * (float)block->steps_e / (float)block->step_event_count) > axis_steps_per_sqr_second[E_AXIS])
651 block->acceleration_st = axis_steps_per_sqr_second[E_AXIS];
652 if(((float)block->acceleration_st * (float)block->steps_z / (float)block->step_event_count ) > axis_steps_per_sqr_second[Z_AXIS])
653 block->acceleration_st = axis_steps_per_sqr_second[Z_AXIS];
654 }
655 block->acceleration = block->acceleration_st / steps_per_mm;
656 block->acceleration_rate = (long)((float)block->acceleration_st * 8.388608);
657
658 #if 0 // Use old jerk for now
659 // Compute path unit vector
660 double unit_vec[3];
661
662 unit_vec[X_AXIS] = delta_mm[X_AXIS]*inverse_millimeters;
663 unit_vec[Y_AXIS] = delta_mm[Y_AXIS]*inverse_millimeters;
664 unit_vec[Z_AXIS] = delta_mm[Z_AXIS]*inverse_millimeters;
665
666 // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
667 // Let a circle be tangent to both previous and current path line segments, where the junction
668 // deviation is defined as the distance from the junction to the closest edge of the circle,
669 // colinear with the circle center. The circular segment joining the two paths represents the
670 // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
671 // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
672 // path width or max_jerk in the previous grbl version. This approach does not actually deviate
673 // from path, but used as a robust way to compute cornering speeds, as it takes into account the
674 // nonlinearities of both the junction angle and junction velocity.
675 double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
676
677 // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
678 if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
679 // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
680 // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
681 double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
682 - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
683 - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
684
685 // Skip and use default max junction speed for 0 degree acute junction.
686 if (cos_theta < 0.95) {
687 vmax_junction = min(previous_nominal_speed,block->nominal_speed);
688 // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
689 if (cos_theta > -0.95) {
690 // Compute maximum junction velocity based on maximum acceleration and junction deviation
691 double sin_theta_d2 = sqrt(0.5*(1.0-cos_theta)); // Trig half angle identity. Always positive.
692 vmax_junction = min(vmax_junction,
693 sqrt(block->acceleration * junction_deviation * sin_theta_d2/(1.0-sin_theta_d2)) );
694 }
695 }
696 }
697 #endif
698 // Start with a safe speed
699 float vmax_junction = max_xy_jerk/2;
700 if(fabs(current_speed[Z_AXIS]) > max_z_jerk/2)
701 vmax_junction = max_z_jerk/2;
702 vmax_junction = min(vmax_junction, block->nominal_speed);
703 if(fabs(current_speed[E_AXIS]) > max_e_jerk/2)
704 vmax_junction = min(vmax_junction, max_e_jerk/2);
705
706 if ((moves_queued > 1) && (previous_nominal_speed > 0.0001)) {
707 float jerk = sqrt(pow((current_speed[X_AXIS]-previous_speed[X_AXIS]), 2)+pow((current_speed[Y_AXIS]-previous_speed[Y_AXIS]), 2));
708 if((fabs(previous_speed[X_AXIS]) > 0.0001) || (fabs(previous_speed[Y_AXIS]) > 0.0001)) {
709 vmax_junction = block->nominal_speed;
710 }
711 if (jerk > max_xy_jerk) {
712 vmax_junction *= (max_xy_jerk/jerk);
713 }
714 if(fabs(current_speed[Z_AXIS] - previous_speed[Z_AXIS]) > max_z_jerk) {
715 vmax_junction *= (max_z_jerk/fabs(current_speed[Z_AXIS] - previous_speed[Z_AXIS]));
716 }
717 if(fabs(current_speed[E_AXIS] - previous_speed[E_AXIS]) > max_e_jerk) {
718 vmax_junction *= (max_e_jerk/fabs(current_speed[E_AXIS] - previous_speed[E_AXIS]));
719 }
720 }
721 block->max_entry_speed = vmax_junction;
722
723 // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
724 double v_allowable = max_allowable_speed(-block->acceleration,MINIMUM_PLANNER_SPEED,block->millimeters);
725 block->entry_speed = min(vmax_junction, v_allowable);
726
727 // Initialize planner efficiency flags
728 // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
729 // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
730 // the current block and next block junction speeds are guaranteed to always be at their maximum
731 // junction speeds in deceleration and acceleration, respectively. This is due to how the current
732 // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
733 // the reverse and forward planners, the corresponding block junction speed will always be at the
734 // the maximum junction speed and may always be ignored for any speed reduction checks.
735 if (block->nominal_speed <= v_allowable) { block->nominal_length_flag = true; }
736 else { block->nominal_length_flag = false; }
737 block->recalculate_flag = true; // Always calculate trapezoid for new block
738
739 // Update previous path unit_vector and nominal speed
740 memcpy(previous_speed, current_speed, sizeof(previous_speed)); // previous_speed[] = current_speed[]
741 previous_nominal_speed = block->nominal_speed;
742
743
744 #ifdef ADVANCE
745 // Calculate advance rate
746 if((block->steps_e == 0) || (block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0)) {
747 block->advance_rate = 0;
748 block->advance = 0;
749 }
750 else {
751 long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_st);
752 float advance = (STEPS_PER_CUBIC_MM_E * advance_k) *
753 (current_speed[E_AXIS] * current_speed[E_AXIS] * EXTRUTION_AREA * EXTRUTION_AREA)*256;
754 block->advance = advance;
755 if(acc_dist == 0) {
756 block->advance_rate = 0;
757 }
758 else {
759 block->advance_rate = advance / (float)acc_dist;
760 }
761 }
762 /*
763 SERIAL_ECHO_START;
764 SERIAL_ECHOPGM("advance :");
765 SERIAL_ECHO(block->advance/256.0);
766 SERIAL_ECHOPGM("advance rate :");
767 SERIAL_ECHOLN(block->advance_rate/256.0);
768 */
769 #endif // ADVANCE
770
771 calculate_trapezoid_for_block(block, block->entry_speed/block->nominal_speed,
772 MINIMUM_PLANNER_SPEED/block->nominal_speed);
773
774 // Move buffer head
775 block_buffer_head = next_buffer_head;
776
777 // Update position
778 memcpy(position, target, sizeof(target)); // position[] = target[]
779
780 planner_recalculate();
781
782 st_wake_up();
783 }
784
785 void plan_set_position(const float &x, const float &y, const float &z, const float &e)
786 {
787 position[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
788 position[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
789 position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
790 position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
791 st_set_position(position[X_AXIS], position[Y_AXIS], position[Z_AXIS], position[E_AXIS]);
792 previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
793 previous_speed[0] = 0.0;
794 previous_speed[1] = 0.0;
795 previous_speed[2] = 0.0;
796 previous_speed[3] = 0.0;
797 }
798
799 void plan_set_e_position(const float &e)
800 {
801 position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
802 st_set_e_position(position[E_AXIS]);
803 }
804
805 uint8_t movesplanned()
806 {
807 return (block_buffer_head-block_buffer_tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1);
808 }
809
810 void allow_cold_extrudes(bool allow)
811 {
812 #ifdef PREVENT_DANGEROUS_EXTRUDE
813 allow_cold_extrude=allow;
814 #endif
815 }

mercurial