-
Notifications
You must be signed in to change notification settings - Fork 75
/
StepperAccelPlanner.cc
1653 lines (1384 loc) · 61.4 KB
/
StepperAccelPlanner.cc
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
/*
StepperAccelPlanner.cc - buffers movement commands and manages the acceleration profile plan
Part of Grbl
Copyright (c) 2009-2011 Simen Svale Skogsrud
Grbl 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.
Grbl 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 Grbl. If not, see <http://www.gnu.org/licenses/>.
The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
This module has been heavily modified from the original Marlin (https://github.com/ErikZalm).
JKN Advance, YAJ (Yet Another Jerk), Advance Pressure Relax and modifications originate from
Jetty Firmware (https://github.com/jetty840/G3Firmware). These modifications and features are
copyrighted and authored by Dan Newman and Jetty under GPL. Copyright (c) 2012.
*/
/*
Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
s == speed, a == acceleration, t == time, d == distance
Basic definitions:
Speed[s_, a_, t_] := s + (a*t)
Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
Distance to reach a specific speed with a constant acceleration:
Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
Speed after a given distance of travel with constant acceleration:
Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
m -> Sqrt[2 a d + s^2]
DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
When to start braking (di) to reach a specified destionation speed (s2) after accelerating
from initial speed s1 without ever stopping at a plateau:
Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
*/
#include "Compat.hh"
#ifdef SIMULATOR
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "Simulator.hh"
#endif
#include "Configuration.hh"
#include "StepperAccel.hh"
#include "StepperAccelPlanner.hh"
#include <stdlib.h>
#include <math.h>
#include <string.h>
#ifndef SIMULATOR
#include <avr/interrupt.h>
#include "Motherboard.hh"
#endif
#ifdef abs
#undef abs
#endif
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(x) ((x)>0?(x):-(x))
#define VEPSILON 1.0e-5
// v1 != v2
#ifdef FIXED
#define VNEQ(v1,v2) ((v1) != (v2))
#define VLT(v1,v2) ((v1) < (v2))
#else
#define VNEQ(v1,v2) (abs((v1)-(v2)) > VEPSILON)
#define VLT(v1,v2) (((v1) + VEPSILON) < (v2))
#endif
volatile bool pipeline_ready = true;
uint32_t max_acceleration_units_per_sq_second[STEPPER_COUNT]; // Use M201 to override by software
FPTYPE smallest_max_speed_change;
FPTYPE max_speed_change[STEPPER_COUNT]; //The speed between junctions in the planner, reduces blobbing
FPTYPE minimumPlannerSpeed;
uint8_t slowdown_limit;
bool disable_slowdown = true;
uint32_t axis_steps_per_sqr_second[STEPPER_COUNT];
#ifdef JKN_ADVANCE
FPTYPE extruder_advance_k = 0, extruder_advance_k2 = 0;
#endif
uint8_t planner_axes;
FPTYPE delta_mm[STEPPER_COUNT];
FPTYPE planner_distance;
uint32_t planner_master_steps;
uint8_t planner_master_steps_index;
int32_t planner_steps[STEPPER_COUNT];
FPTYPE vmax_junction;
uint32_t axis_accel_step_cutoff[STEPPER_COUNT];
#ifdef CORE_XY
int32_t delta_ab[2];
#elif CORE_XYZ
int32_t delta_ab[3];
#endif
// minimum time in seconds that a movement needs to take if the buffer is emptied.
// Increase this number if you see blobs while printing high speed & high detail.
// It will slowdown on the detailed stuff.
// Comment out to disable
FPTYPE minimumSegmentTime;
// The current position of the tool in absolute steps
int32_t planner_position[STEPPER_COUNT]; //rescaled from extern when axisStepsPerMM are changed by gcode
int32_t planner_target[STEPPER_COUNT];
static FPTYPE prev_speed[STEPPER_COUNT];
static FPTYPE prev_final_speed = 0;
#ifdef SIMULATOR
static block_t *sblock = NULL;
#endif
bool acceleration_zhold = true;
#ifdef DEBUG_BLOCK_BY_MOVE_INDEX
uint32_t current_move_index = 0;
#endif
#if defined(FIXED) && ! defined(SIMULATOR)
//http://members.chello.nl/j.beentjes3/Ruud/sqrt32avr.htm
static int16_t isqrt1(int16_t value)
{
int16_t result;
asm volatile (
"; Fast and short 16 bits AVR sqrt routine" "\n\t"
";" "\n\t"
"; R17:R16 = sqrt(R3:R2), rounded down to integer" "\n\t"
";" "\n\t"
"; Registers:" "\n\t"
"; Destroys the argument in R3:R2" "\n\t"
";" "\n\t"
"; Cycles incl call & ret = 90 - 96" "\n\t"
";" "\n\t"
"; Stack incl call = 2" "\n\t"
"Sqrt16: ldi %B0,0xc0 ; Rotation mask register" "\n\t"
" ldi %A0,0x40 ; Developing sqrt" "\n\t"
" clc ; Enter loop with C=0" "\n\t"
"_sq16_1: brcs _sq16_2 ; C --> Bit is always 1" "\n\t"
" cp %B1,%A0 ; Does value fit?" "\n\t"
" brcs _sq16_3 ; C --> bit is 0" "\n\t"
"_sq16_2: sub %B1,%A0 ; Adjust argument for next bit" "\n\t"
" or %A0,%B0 ; Set bit to 1" "\n\t"
"_sq16_3: lsr %B0 ; Shift right rotation mask" "\n\t"
" lsl %A1" "\n\t"
" rol %B1 ; Shift left argument, C --> Next sub is MUST" "\n\t"
" eor %A0,%B0 ; Shift right test bit in developing sqrt" "\n\t"
" andi %B0,0xfe ; Becomes 0 for last bit" "\n\t"
" brne _sq16_1 ; Develop 7 bits" "\n\t"
" brcs _sq16_4 ; C--> Last bit always 1" "\n\t"
" lsl %A1 ; Need bit 7 in C for cpc" "\n\t"
" cpc %A0,%B1 ; After this C is last bit" "\n\t"
"_sq16_4: adc %A0,%B0 ; Set last bit if C (R17=0)" "\n\t"
: "=&r" (result)
: "r" (value)
);
return result;
}
#endif
block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instfructions
volatile unsigned char block_buffer_head; // Index of the next block to be pushed
volatile unsigned char block_buffer_tail; // Index of the block to process now
// Returns the index of the next block in the ring buffer
// NOTE: Removed modulo (%) operator, which uses an expensive divide and multiplication.
#ifndef SAVE_SPACE
FORCE_INLINE
#endif
static uint8_t next_block_index(uint8_t block_index) {
block_index++;
if (block_index == BLOCK_BUFFER_SIZE) { block_index = 0; }
return(block_index);
}
// Returns the index of the previous block in the ring buffer
#ifndef SAVE_SPACE
FORCE_INLINE
#endif
static uint8_t prev_block_index(uint8_t block_index) {
if (block_index == 0) { block_index = BLOCK_BUFFER_SIZE; }
block_index--;
return(block_index);
}
// Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the
// given acceleration:
// Note the equation used below is EXACT: there's no "estimation" involved.
// As such, the name is a bit misleading.
// t = time
// a = acceleration (constant)
// d(t) = distance travelled at time t
// initial_rate = rate of travel at time t = 0
// rate(t) = rate of travel at time t
//
// From basic kinematics, we have
//
// [1] d(t) = d(0) + initial_rate * t + 0.5 * a * t^2,
//
// and
//
// [2] rate(t) = initial_rate + a * t.
//
// For our purposes, d(0)
//
// [3] d(0) = 0.
//
// Solving [2] for time t, gives us
//
// [4] t = ( rate(t) - initial_rate ) / a.
//
// Substituting [3] and [4] into [1] produces,
//
// [5] d(t) = initial_rate * ( rate(t) - intial_rate ) / a + ( rate(t) - initial_rate )^2 / 2a.
//
// With some algebraic simplification, we then find that d(t) is given by
//
// [6] d(t) = ( rate(t)^2 - initial_rate^2 ) / 2a.
//
// So, if we know our desired initial rate, initial_rate, and our acceleration, the distance d
// required to reach a target rate, target_rate, is then
//
// [7] d = ( target_rate^2 - initial_rate^2 ) / 2a.
//
// Note that if the acceleration is 0, we can never reach the target rate unless the
// initial and target rates are the same. This stands to reason since if the acceleration
// is zero, then our speed never changes and thus no matter how far we move, we're still
// moving at our initial speed.
FORCE_INLINE int32_t estimate_acceleration_distance(int32_t initial_rate_sq, int32_t target_rate_sq, int32_t acceleration_doubled)
{
if (acceleration_doubled!=0) {
return((target_rate_sq-initial_rate_sq)/acceleration_doubled);
} else {
return 0; // acceleration was 0, set acceleration distance to 0
}
}
// This function gives you the point at which you must start braking (at the rate of -acceleration) if
// you started at speed initial_rate and accelerated until this point and want to end at the final_rate after
// a total travel of distance. This can be used to compute the intersection point between acceleration and
// deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed)
//
// accelerate +a decelerate -a
// |<---- d1 ---->|<---------- d2 ---------->|
// |<------------- d = d1 + d2 ------------->|
// t=0 t=t1 t=t1+t2
// initial_rate peak_rate final_rate
//
// From basic kinematics,
//
// [1] d1 = initial_rate t1 + 0.5 a t1^2
// [2] d2 = final_rate t2 + 0.5 a t2^2 [think of starting at speed final_rate and accelerating by a]
// [3] final_rate = initial_rate + a (t1 - t2)
// [4] d2 = d - d1
//
// We wish to solve for d1 given a, d, initial_rate, and final_rate.
// By the quadratic equation,
//
// [5] t1 = [ -initial_rate +/- sqrt( initial_rate^2 + 2 a d1 ) ] / a
// [6] t2 = [ -final_rate +/- sqrt( final_rate^2 + 2 a d2 ) ] / a
//
// Replacing t1 and t2 in [6] then produces,
//
// [7] final_rate = initial_rate - initial_rate +/- sqrt( initial_rate^2 + 2 a d1 ) +
// + final_rate -/+ sqrt( final_rate^2 + 2 a d2 )
//
// And thus,
//
// [8] +/- sqrt( initial_rate^2 + 2 a d1 ) = +/- sqrt( final_rate^2 + 2 a d2 )
//
// Squaring both sides and substituting d2 = d - d1 [4] yields,
//
// [9] initial_rate^2 + 2 a d1 = final_rate^2 + 2 a d - 2 a d1
//
// Solving [9] for d1 then gives our desired result,
//
// [10] d1 = ( final_rate^2 - initial_rate^2 + 2 a d ) / 4a
FORCE_INLINE int32_t intersection_distance(int32_t initial_rate_sq, int32_t final_rate_sq, int32_t acceleration_doubled, int32_t distance)
{
if (acceleration_doubled!=0) {
return((acceleration_doubled*distance-initial_rate_sq+final_rate_sq)/(acceleration_doubled << 1) );
} else {
return 0; // acceleration was 0, set intersection distance to 0
}
}
#ifdef JKN_ADVANCE
// Same as final_speed, except this one works with step_rates.
// Regular final_speed will overflow if we use step_rates instead of mm/s
FORCE_INLINE FPTYPE final_speed_step_rate(uint32_t acceleration, uint32_t initial_velocity, int32_t distance) {
uint32_t v2 = initial_velocity * initial_velocity;
#ifdef SIMULATOR
uint64_t sum2 = (uint64_t)initial_velocity * (uint64_t)initial_velocity +
2 * (uint64_t)acceleration * (uint64_t)distance;
float fres = (sum2 > 0) ? sqrt((float)sum2) : 0.0;
FPTYPE result;
#endif
// Although it's highly unlikely, if target_rate < initial_rate, then distance could be negative.
if ( distance < 0 ) {
uint32_t term2 = (acceleration * (uint32_t)abs(distance)) << 1;
if ( term2 >= v2 ) return 0;
v2 -= term2;
}
else v2 += (acceleration * (uint32_t)distance) << 1;
if (v2 <= 0x7fff)
#ifndef SIMULATOR
return ITOFP(isqrt1((uint16_t)v2));
#else
#ifndef isqrt1
#define isqrt1(x) ((int32_t)sqrt((float)(x)))
#endif
result = ITOFP(isqrt1((uint16_t)v2));
#endif
else {
uint8_t n = 0;
while (v2 > 0x7fff) {
v2 >>= 2;
n++;
}
#ifndef SIMULATOR
return ITOFP(isqrt1((int16_t)v2)) << n;
#else
result = ITOFP(isqrt1((int16_t)v2)) << n;
#endif
}
#ifdef SIMULATOR
if ((fres != 0.0) && ((fabsf(fres - FPTOF(result))/fres) > 0.01)) {
char buf[1024];
snprintf(buf, sizeof(buf), "!!! final_speed_step_rate(%d, %d, %d): fixed result = %f; "
"float result = %f !!!\n", acceleration, initial_velocity, distance,
FPTOF(result), fres);
if (sblock) strlcat(sblock->message, buf, sizeof(sblock->message));
else printf("%s", buf);
}
return result;
#endif
}
#endif
// Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors.
void calculate_trapezoid_for_block(block_t *block, FPTYPE entry_factor, FPTYPE exit_factor) {
// If exit_factor or entry_factor are larger than unity, then we will scale
// initial_rate or final_rate to exceed nominal_rate. However, maximum feed rates
// have been applied to nominal_rate and as such we should not exceed nominal_rate.
// For example, if the next block's entry_speed exceeds this block's nominal_speed,
// then we can be called with exit_factor = next->entry_speed / current->nominal_speed > 1.
// Basically, that's saying that the next block's nominal speed which was subject to
// per axis feed rates for a different combination of axes steps can override this block's
// speed limits. We don't want that. For example, if this block's motion is primarily
// Z or E axis steps and the next block's is all X axis steps, we don't want the next
// block's X-axis limited entry_speed telling this block that it's Z or E axis limited
// final_rate can be increased past the block's nominal_rate.
if ( (!block->use_accel) || (entry_factor > KCONSTANT_1) ) entry_factor = KCONSTANT_1;
if ( (!block->use_accel) || (exit_factor > KCONSTANT_1) ) exit_factor = KCONSTANT_1;
uint32_t initial_rate = (uint32_t)FPTOI(FPCEIL(FPMULT2(ITOFP(block->nominal_rate), entry_factor))); // (step/min)
uint32_t final_rate = (uint32_t)FPTOI(FPCEIL(FPMULT2(ITOFP(block->nominal_rate), exit_factor))); // (step/min)
// If we really need to squeeze cyles, then we can instead do the following
// but then we'd be testing for rates < 128
// if (0 == (initial_rate & 0xffffff80)) initial_rate=127; // initial_rate < 127
// if (0 == (final_rate & 0xffffff80)) final_rate=127; // final_rate < 127
// Limit minimal step rate (Otherwise the timer will overflow.)
if ( initial_rate < 120 ) initial_rate = 120;
if ( final_rate < 120 ) final_rate = 120;
int32_t initial_rate_sq = (int32_t)(initial_rate * initial_rate);
int32_t final_rate_sq = (int32_t)(final_rate * final_rate);
int32_t acceleration = block->acceleration_st;
int32_t acceleration_doubled = acceleration << 1;
int32_t accelerate_steps = 0;
int32_t decelerate_steps = 0;
if ( block->use_accel ) {
accelerate_steps = estimate_acceleration_distance(initial_rate_sq, block->nominal_rate_sq, acceleration_doubled);
decelerate_steps = estimate_acceleration_distance(block->nominal_rate_sq, final_rate_sq, -acceleration_doubled);
}
// accelerate_steps = max(accelerate_steps,0); // Check limits due to numerical round-off
// accelerate_steps = min(accelerate_steps,(int32_t)block->step_event_count);
// Calculate the size of Plateau of Nominal Rate.
int32_t plateau_steps = block->step_event_count-accelerate_steps-decelerate_steps;
// Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
// have to use intersection_distance() to calculate when to abort acceleration and start braking
// in order to reach the final_rate exactly at the end of this block.
if (plateau_steps < 0) {
accelerate_steps = intersection_distance(initial_rate_sq, final_rate_sq, acceleration_doubled, (int32_t)block->step_event_count);
accelerate_steps = max(accelerate_steps,0); // Check limits due to numerical round-off
accelerate_steps = min(accelerate_steps,(int32_t)block->step_event_count);
plateau_steps = 0;
}
int32_t decelerate_after = accelerate_steps + plateau_steps;
#ifdef JKN_ADVANCE
#ifdef SIMULATOR
sblock = block;
#endif
int16_t advance_lead_entry = 0, advance_lead_exit = 0, advance_lead_prime = 0, advance_lead_deprime = 0;
int32_t advance_pressure_relax = 0;
if ( block->use_advance_lead ) {
uint32_t maximum_rate;
// Note that we accelerate between step 0 & 1, between 1 & 2, ..., between
// acclerate_steps-1 & accelerate_steps, AND accelerate_steps & accelerate_steps+1
// So, we accelerate for accelerate_steps + 1. This is because in st_interrupt()
// the test is "if (step_events_completed <= accelerate_until)" which means that
// between step accelerate_until and the next step, we're still doing acceleration.
if ( plateau_steps == 0 ) maximum_rate = FPTOI(final_speed_step_rate(block->acceleration_st, initial_rate,
accelerate_steps + 1));
else maximum_rate = block->nominal_rate;
// Don't waste cycles computing these values if we won't use them in st_interrupt()
if (accelerate_steps > 0) {
#ifdef JKN_ADVANCE_LEAD_ACCEL
// acceleration_st is in units of steps/s^2
// On the ToM with 1/8th stepping we use >> 4
// On the Replicator with 1/16th stepping we use >> 5
// This makes the overflow ranges comparable in mm/s^2 units AND makes the K ranges comparable
// Acceleration limit to prevent overflow is 0xFFFFF / axis-steps-per-mm
advance_lead_entry = FPTOI16(FPMULT2(extruder_advance_k, ITOFP((int32_t)block->acceleration_st >> (1+MICROSTEPPING)));
#else
// Acceleration dependent portion
// Basis of computation is as follows. Suppose the filament velocity, Vf, should be
//
// [1] Vf = C1 * Vn + C2 * a
//
// where
//
// Vn = extruded noodle velocity
// a = acceleration
// C1 = constant (ratio of volumes and whatnot)
// C2 = another constant
//
// But we're normally just taking Vf = C1 * Vn and thus we're missing a contribution
// associated with acceleration (e.g., a contribution associated with energy loss to
// friction in the extruder nozzle). We can then ask, well how many e-steps do we
// miss as a result? Using,
//
// [2] distance in e-space = velocity x time
//
// we would then appear to be missing
//
// [3] delta-e = C2 * a * time-spent-accelerating
//
// From basic kinematics, we know the time spent accelerating under constant acceleration,
//
// [4] Vfinal = Vinitial + a * time-spent-accelerating
//
// and thus
//
// [5] time-spent-accelerating = (Vfinal - Vinitial) / a
//
// Substituting [5] into [3] yields,
//
// [6] delta-e = C2 * (Vfinal - Vinitial)
//
// where Vinitial and Vfinal are the initial and final speeds
// at the start and end of the acceleration or deceleration phase.
advance_lead_entry = FPTOI16(FPMULT2(extruder_advance_k, ITOFP((int32_t)(maximum_rate - initial_rate))));
#endif
#ifdef JKN_ADVANCE_LEAD_DE_PRIME
// Prime. Same as advance_lead_entry, but for when we're priming from 0 to initial_rate
// Note that we may or may not use this value, it's only used if the previous segment was not available or had e steps of 0
advance_lead_prime = FPTOI16(FPMULT2(extruder_advance_k, ITOFP((int32_t)initial_rate)) - KCONSTANT_0_5);
#endif
#ifndef SIMULATOR
if (advance_lead_entry < 0) advance_lead_entry = 0;
if (advance_lead_prime < 0) advance_lead_prime = 0;
#endif
}
if ((decelerate_after+1) < (int32_t)block->step_event_count) {
#ifdef JKN_ADVANCE_LEAD_ACCEL
// acceleration_st is in units of steps/s^2
// On the ToM with 1/8th stepping we use >> 4
// On the Replicator with 1/16th stepping we use >> 5
// This makes the overflow ranges comparable in mm/s^2 units AND makes the K ranges comparable
// Acceleration limit to prevent overflow is 0xFFFFF / axis-steps-per-mm
advance_lead_exit = FPTOI16(FPMULT2(extruder_advance_k, ITOFP((int32_t)block->acceleration_st >> (1+MICROSTEPPING)));
#else
// Acceleration dependent portion
advance_lead_exit = FPTOI16(FPMULT2(extruder_advance_k, ITOFP((int32_t)(maximum_rate - final_rate))));
#endif
#ifdef JKN_ADVANCE_LEAD_DE_PRIME
// Deprime. Same as advance_lead_exit, but for when we're depriming from final_rate to 0
// Note that we may or may not use this value, it's only used if the next segment is not available or has e steps of 0
advance_lead_deprime = FPTOI16(FPMULT2(extruder_advance_k, ITOFP((int32_t)final_rate)) - KCONSTANT_0_5);
#endif
//Pressure relaxation
if ( extruder_advance_k2 != 0 ) {
// acceleration_st is in units of steps/s^2
// On the ToM with 1/8th stepping we use >> 4
// On the Replicator with 1/16th stepping we use >> 5
// Acceleration limit to prevent overflow is 0xFFFFF / axis-steps-per-mm
advance_pressure_relax =
FPTOI(FPMULT3(extruder_advance_k2, KCONSTANT_100,
FPDIV(ITOFP((int32_t)block->acceleration_st >> (1+MICROSTEPPING)),
ITOFP((int32_t)decelerate_steps))));
}
#ifndef SIMULATOR
//If we've overflowed, reset to 0
if ( advance_pressure_relax < 0 ) advance_pressure_relax = 0;
if (advance_lead_exit < 0) advance_lead_exit = 0;
if (advance_lead_deprime < 0) advance_lead_deprime = 0;
#endif
}
#ifdef SIMULATOR
// Owing to roundoff errors, it's not abnormal to see values of -1
if ( (advance_lead_entry < -1) || (advance_lead_exit < -1) || (advance_pressure_relax < 0) || (advance_pressure_relax >> 8) > 0x7fff) {
char buf[1024];
snprintf(buf, sizeof(buf),
"!!! calculate_trapezoid_for_block(): advance_lead_entry=%d, advance_lead_exit=%d, "
"advance_pressure_relax=%d; initial/nominal/maximum/final_rate=%d/%d/%d/%d; "
"accelerate_until/decelerate_after/step_events/plateau_steps=%d/%d/%d/%d; "
"i/n/f/a=%d/%d/%d/%d !!!\n",
advance_lead_entry, advance_lead_exit, advance_pressure_relax,initial_rate, block->nominal_rate,
maximum_rate, final_rate, accelerate_steps, decelerate_after, block->step_event_count,
plateau_steps, initial_rate_sq, block->nominal_rate_sq, final_rate_sq, acceleration_doubled);
strlcat(block->message, buf, sizeof(block->message));
}
#endif
}
#endif
CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
if(block->busy == false) { // Don't update variables if block is busy.
if ( block->use_accel ) {
block->accelerate_until = accelerate_steps;
block->decelerate_after = decelerate_after;
}
block->initial_rate = initial_rate;
block->final_rate = final_rate;
#ifdef JKN_ADVANCE
block->advance_lead_entry = advance_lead_entry;
block->advance_lead_exit = advance_lead_exit;
block->advance_lead_prime = advance_lead_prime;
block->advance_lead_deprime = advance_lead_deprime;
block->advance_pressure_relax = advance_pressure_relax;
#endif
}
CRITICAL_SECTION_END;
#ifdef SIMULATOR
block->planned += 1;
#endif
}
// Calculates the final speed (terminal speed) which will be attained if we start at
// speed initial_velocity and then accelerate at the given rate over the given distance
// From basic kinematics, we know that displacement d(t) at time t for an object moving
// initially at speed v0 and subject to constant acceleration a is given by
//
// [1] d(t) = v0 t + 0.5 a t^2, t >= 0
//
// We also know that the speed v(t) at time t is governed by
//
// [2] v(t) = v0 + a t
//
// Now, without reference to time, we desire to find the speed v_final we will
// find ourselves moving at after travelling a given distance d. To find an answer
// to that question, we need to solve one of the two above equations for t and
// then substitute the result into the remaining equation. As it turns out, the
// algebra is a little easier whne [1] is solved for t using the quadratic
// equation then first solving [2] for t and then plugging into [1] and then
// solving the result for v(t) with the quadratic equation.
//
// So, moving forward and solving [1] for t via the quadratic equation, gives
//
// [3] t = - [ v0 +/- sqrt( v0^2 - 2ad(t) ) ] / a
//
// Substituting [3] into [2] then
//
// [4] v(t) = v0 - [ v0 +/- sqrt( v0^2 + 2ad(t) ) ]
//
// With some minor simplification and droping the (t) notation, we then have
//
// [5] v = -/+ sqrt( v0^2 + 2ad )
//
// With equation [5], we then know the final speed v attained after accelerating
// from initial speed v0 over distance d.
FORCE_INLINE FPTYPE final_speed(FPTYPE acceleration, FPTYPE initial_velocity, FPTYPE distance) {
#ifdef FIXED
// static int counts = 0;
#ifdef SIMULATOR
float ftv = FPTOF(initial_velocity);
float fac = FPTOF(acceleration);
float fd = FPTOF(distance);
float fres = ftv * ftv + 2.0 * fac * fd;
if (fres <= 0.0) fres = 0.0;
else fres = sqrt(fres);
#endif
// We wish to compute
//
// sum2 = initial_velocity * initial_velocity + 2 * acceleration * distance
//
// without having any overflows. We therefore judiciously divide
// both summands by 2^12. After computing sqrt(sum2), we will the
// multiply the result by 2^6 which is he square root of 2^12.
// Note that when initial_velocity < 1, we lose velocity resolution.
// When acceleration or distance are < 1, we lose some resolution
// in them as well. We're here taking advantage of the fact that
// the acceleration is usually pretty large as are the velocities.
// Only the distances are sometimes small which is why we shift the
// distance the least. If this were to become a problem, we could
// shift the acceleration more and the distance even less. And,
// when the velocity is tiny relative to the product 2 * a * d,
// we really don't care as 2 * a * d will then dominate anyway.
// That is, losing resolution in the velocity is not, in practice,
// harmful since 2 * a * d will likely dominate in that case.
// 2 * (distance >> 6) == distance >> 5
// We don't use FP macros for initial_velocity, because it is no longer
// valid when we've shifted. Instead we do it manually, shifting by the
// right amount to get the right answer.
uint16_t initial_velocity_12 = initial_velocity >> 12;
FPTYPE sum2 = ((initial_velocity_12 * initial_velocity_12) >> 4) + (FPMULT2(distance, acceleration >> 6) >> 5);
// Now, comes the real speed up: use our fast 16 bit integer square
// root (in assembler nonetheles). To pave the way for this, we shift
// sum2 as much to the left as possible thereby maximizing the use of
// the "whole" or "integral" part of the fixed point number. We then
// take the square root of the integer part of sum2 which has been
// multiplied by 2^(2n) [n left shifts by 2]. After taking the square
// root, we correct this scaling by dividing the result by 2^n (which
// is the square root of 2^(2n)
uint8_t n = 0;
while ((sum2 != 0) && (sum2 & 0xe0000000) == 0) {
sum2 <<= 2;
n++;
}
// Generate the final result. We need to undo two sets of
// scalings: our original division by 2^12 which we rectify
// by multiplying by 2^6. But also we need to divide by 2^n
// so as to counter the 2^(2n) scaling we did. This means
// a net multiply by 2^(6-n).
FPTYPE result;
if (sum2 <= 0) {
if (acceleration < 0 )
result = 0;
else
result = initial_velocity;
}
else {
result = ITOFP(isqrt1(FPTOI16(sum2)));
if (n > 6) result >>= (n - 6);
else result <<= (6 - n);
}
#ifndef SIMULATOR
return result;
//#ifdef DEBUG_ONSCREEN
// Timing code
// FPTYPE result;
// if (sum2 <= 0) result = 0;
// else if (n > 6) result = ITOFP(isqrt1(FPTOI16(sum2))) >> (n - 6);
// else result = ITOFP(isqrt1(FPTOI16(sum2))) << (6 - n);
// DEBUG_TIMER_FINISH;
// debug_onscreen2 += DEBUG_TIMER_TCTIMER_US;
// counts += 1;
// debug_onscreen1 = debug_onscreen2 / counts;
// return result;
//#endif
#else
if ((fres != 0.0) && (fabsf(fres - FPTOF(result)) > 1 && (fabsf(fres - FPTOF(result))/fres) > 0.02)) {
char buf[1024];
snprintf(buf, sizeof(buf),
"!!! final_speed(%6.2f:%#10x, %6.2f:%#10x, %7.3f:%#10x): n = %2d sum2 = %8.2f fixed result = %6.2f; float result = %6.2f error = %4.0f%% !!!\n",
FPTOF(acceleration),acceleration,
FPTOF(initial_velocity), initial_velocity,
FPTOF(distance), distance,
n,
FPTOF(sum2),
FPTOF(result), fres,
(100*fres/FPTOF(result))-100);
if (sblock) strlcat(sblock->message, buf, sizeof(sblock->message));
else printf("%s", buf);
}
return result;
#endif // SIMULATOR
#else
// Just assume we're doing everything with floating point arithmetic
// and do not need to worry about overflows or underflows
FPTYPE v2 = FPSQUARE(initial_velocity) + FPSCALE2(FPMULT2(acceleration, distance));
if (v2 <= 0) return 0;
else return FPSQRT(v2);
#endif // !FIXED
}
// The kernel called by planner_recalculate() when scanning the plan from last to first entry.
void planner_reverse_pass_kernel(block_t *current, block_t *next) {
if (!current) { return; }
if (next) {
// If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
// If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
// check for maximum allowable speed reductions to ensure maximum possible planned speed.
if ((current->max_entry_speed - current->entry_speed) > KCONSTANT_3) {
// If nominal length true, max junction speed is guaranteed to be reached. Only compute
// for max allowable speed if block is decelerating and nominal length is false.
if ((!current->nominal_length_flag) && next->speed_changed && (current->max_entry_speed > next->entry_speed)) {
// We want to know what speed to start at so that if we decelerate -- negative acceleration --
// over distance current->millimeters, we end up at speed next->entry_speed
#ifdef SIMULATOR
sblock = current;
#endif
current->entry_speed = min( current->max_entry_speed,
final_speed(-current->acceleration,next->entry_speed,current->millimeters));
} else {
current->entry_speed = current->max_entry_speed;
}
current->speed_changed = true;
current->recalculate_flag = true;
}
} // Skip last block. Already initialized and set for recalculation.
}
// planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This
// implements the reverse pass.
void planner_reverse_pass() {
uint8_t block_index = block_buffer_head;
block_t *block[2] = { NULL, NULL};
//Make a local copy of block_buffer_tail, because the interrupt can alter it
CRITICAL_SECTION_START;
unsigned char tail = block_buffer_tail;
CRITICAL_SECTION_END;
while(block_index != tail) {
block_index = prev_block_index(block_index);
block[1]= block[0];
block[0] = &block_buffer[block_index];
planner_reverse_pass_kernel(block[0], block[1]);
}
}
// The kernel called by planner_recalculate() when scanning the plan from first to last entry.
void planner_forward_pass_kernel(block_t *previous, block_t *current) {
if (!previous || !current->use_accel) { return; }
// If the previous block is an acceleration block, but it is not long enough to complete the
// full speed change within the block, we need to adjust the entry speed accordingly. Entry
// speeds have already been reset, maximized, and reverse planned by reverse planner.
// If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
if (!previous->nominal_length_flag && previous->speed_changed) {
if ((((previous->nominal_speed) < current->nominal_speed) &&
((previous->entry_speed + KCONSTANT_3) > current->entry_speed)) ||
(((previous->nominal_speed) > current->nominal_speed) &&
((previous->entry_speed + KCONSTANT_3) < current->entry_speed))) {
// We want to know what the terminal speed from the prior block would be if
// it accelerated over the entire block with starting speed prev->entry_speed
#ifdef SIMULATOR
sblock = previous;
#endif
FPTYPE entry_speed = min( current->entry_speed,
final_speed(previous->acceleration,previous->entry_speed,previous->millimeters) );
// Check for junction speed change
if (VNEQ(current->entry_speed, entry_speed)) {
current->entry_speed = entry_speed;
current->recalculate_flag = true;
current->speed_changed = true;
}
}
}
}
// planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This
// implements the forward pass.
void planner_forward_pass() {
uint8_t block_index = block_buffer_tail;
block_t *block[2] = { NULL, NULL };
while(block_index != block_buffer_head) {
block[0] = block[1];
block[1] = &block_buffer[block_index];
planner_forward_pass_kernel(block[0],block[1]);
block_index = next_block_index(block_index);
}
}
// Recalculates the trapezoid speed profiles for all blocks in the plan according to the
// entry_factor for each junction. Must be called by planner_recalculate() after
// updating the blocks.
void planner_recalculate_trapezoids() {
uint8_t block_index = block_buffer_tail;
block_t *current;
block_t *next = NULL;
while(block_index != block_buffer_head) {
current = next;
next = &block_buffer[block_index];
if (current && current->use_accel && next->use_accel) {
// Recalculate if current block entry or exit junction speed has changed.
if (current->recalculate_flag || next->recalculate_flag) {
// NOTE: Entry and exit factors always > 0 by all previous logic operations.
calculate_trapezoid_for_block(current, FPDIV(current->entry_speed,current->nominal_speed),
FPDIV(next->entry_speed,current->nominal_speed));
current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed
}
}
block_index = next_block_index( block_index );
}
// Last/newest block in buffer. Exit speed is set with minimumPlannerSpeed. Always recalculated.
if(next != NULL) {
FPTYPE scaling = FPDIV(next->entry_speed,next->nominal_speed);
calculate_trapezoid_for_block(next, scaling, scaling);
// calculate_trapezoid_for_block(next,
// FPDIV(next->entry_speed,next->nominal_speed),
// FPDIV(minimumPlannerSpeed,next->nominal_speed));
next->recalculate_flag = false;
}
}
// Recalculates the motion plan according to the following algorithm:
//
// 1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_factor)
// so that:
// a. The junction jerk is within the set limit
// b. No speed reduction within one block requires faster deceleration than the one, true constant
// acceleration.
// 2. Go over every block in chronological order and dial down junction speed reduction values if
// a. The speed increase within one block would require faster accelleration than the one, true
// constant acceleration.
//
// When these stages are complete all blocks have an entry_factor that will allow all speed changes to
// be performed using only the one, true constant acceleration, and where no junction jerk is jerkier than
// the set limit. Finally it will:
//
// 3. Recalculate trapezoids for all blocks.
void planner_recalculate() {
planner_reverse_pass();
planner_forward_pass();
planner_recalculate_trapezoids();
}
void plan_init(FPTYPE extruderAdvanceK, FPTYPE extruderAdvanceK2, bool zhold) {
#ifdef SIMULATOR
if ( (B_AXIS+1) != STEPPER_COUNT ) abort();
if ( (X_AXIS >= STEPPER_COUNT)
|| (Y_AXIS >= STEPPER_COUNT)
|| (Z_AXIS >= STEPPER_COUNT)
|| (A_AXIS >= STEPPER_COUNT)
#if EXTRUDERS > 1
|| (B_AXIS >= STEPPER_COUNT)
#endif
) abort();
#endif
block_buffer_head = 0;
block_buffer_tail = 0;
// clear planner_position & prev_speed info
prev_final_speed = 0;
for ( uint8_t i = 0; i < STEPPER_COUNT; i ++ )
{
prev_speed[i] = 0;
planner_position[i] = 0;
}
#ifdef JKN_ADVANCE
extruder_advance_k = extruderAdvanceK;
extruder_advance_k2 = extruderAdvanceK2;
#endif
acceleration_zhold = zhold;
disable_slowdown = true;
#ifdef DEBUG_BLOCK_BY_MOVE_INDEX
current_move_index = 0;
#endif
}
// Add a new linear movement to the buffer.
// planner_target[5] should be set outside this function prior to entry to denote the
// absolute target position in steps.
// icroseconds specify how many microseconds the move should take to perform. To aid acceleration
// calculation the caller must also provide the physical length of the line in millimeters.
// The stepper module, gaurantees this never gets called with 0 steps
void plan_buffer_line(FPTYPE feed_rate, const uint32_t &dda_rate, const uint8_t &extruder, bool use_accel, uint8_t active_toolhead)
{