-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmotion.cpp
2135 lines (2031 loc) · 82.7 KB
/
motion.cpp
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
/*
This file is part of Repetier-Firmware.
Repetier-Firmware 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.
Repetier-Firmware 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 Repetier-Firmware. If not, see <http://www.gnu.org/licenses/>.
This firmware is a nearly complete rewrite of the sprinter firmware
by kliment (https://github.com/kliment/Sprinter)
which based on Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware.
Functions in this file are used to communicate using ascii or repetier protocol.
*/
#include "Repetier.h"
// ================ Sanity checks ================
#ifndef STEP_DOUBLER_FREQUENCY
#error Please add new parameter STEP_DOUBLER_FREQUENCY to your configuration.
#else
#if STEP_DOUBLER_FREQUENCY<10000 || STEP_DOUBLER_FREQUENCY>20000
#error STEP_DOUBLER_FREQUENCY should be in range 10000-16000.
#endif
#endif
#ifdef EXTRUDER_SPEED
#error EXTRUDER_SPEED is not used any more. Values are now taken from extruder definition.
#endif
#if MAX_HALFSTEP_INTERVAL<=1900
#error MAX_HALFSTEP_INTERVAL must be greater then 1900
#endif
#ifdef ENDSTOPPULLUPS
#error ENDSTOPPULLUPS is now replaced by individual pullup configuration!
#endif
#ifdef EXT0_PID_PGAIN
#error The PID system has changed. Please use the new float number options!
#endif
// ####################################################################################
// # No configuration below this line - just some errorchecking #
// ####################################################################################
#ifdef SUPPORT_MAX6675
#if !defined SCK_PIN || !defined MOSI_PIN || !defined MISO_PIN
#error For MAX6675 support, you need to define SCK_PIN, MISO_PIN and MOSI_PIN in pins.h
#endif
#endif
#if X_STEP_PIN<0 || Y_STEP_PIN<0 || Z_STEP_PIN<0
#error One of the following pins is not assigned: X_STEP_PIN,Y_STEP_PIN,Z_STEP_PIN
#endif
#if EXT0_STEP_PIN<0 && NUM_EXTRUDER>0
#error EXT0_STEP_PIN not set to a pin number.
#endif
#if EXT0_DIR_PIN<0 && NUM_EXTRUDER>0
#error EXT0_DIR_PIN not set to a pin number.
#endif
#if MOVE_CACHE_SIZE<4
#error MOVE_CACHE_SIZE must be at least 5
#endif
//Inactivity shutdown variables
millis_t previousMillisCmd = 0;
millis_t maxInactiveTime = MAX_INACTIVE_TIME*1000L;
millis_t stepperInactiveTime = STEPPER_INACTIVE_TIME*1000L;
long baudrate = BAUDRATE; ///< Communication speed rate.
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
int maxadv = 0;
#endif
int maxadv2 = 0;
float maxadvspeed = 0;
#endif
uint8_t pwm_pos[NUM_EXTRUDER+3]; // 0-NUM_EXTRUDER = Heater 0-NUM_EXTRUDER of extruder, NUM_EXTRUDER = Heated bed, NUM_EXTRUDER+1 Board fan, NUM_EXTRUDER+2 = Fan
volatile int waitRelax = 0; // Delay filament relax at the end of print, could be a simple timeout
PrintLine PrintLine::lines[MOVE_CACHE_SIZE]; ///< Cache for print moves.
PrintLine *PrintLine::cur = 0; ///< Current printing line
#if CPU_ARCH==ARCH_ARM
volatile bool PrintLine::nlFlag = false;
#endif
uint8_t PrintLine::linesWritePos = 0; ///< Position where we write the next cached line move.
volatile uint8_t PrintLine::linesCount = 0; ///< Number of lines cached 0 = nothing to do.
uint8_t PrintLine::linesPos = 0; ///< Position for executing line movement.
/**
Move printer the given number of steps. Puts the move into the queue. Used by e.g. homing commands.
*/
void PrintLine::moveRelativeDistanceInSteps(long x,long y,long z,long e,float feedrate,bool waitEnd,bool checkEndstop)
{
//Com::printF(Com::tJerkColon,x);
//Com::printF(Com::tComma,y);
//Com::printFLN(Com::tComma,z);
float savedFeedrate = Printer::feedrate;
Printer::destinationSteps[X_AXIS] = Printer::currentPositionSteps[X_AXIS] + x;
Printer::destinationSteps[Y_AXIS] = Printer::currentPositionSteps[Y_AXIS] + y;
Printer::destinationSteps[Z_AXIS] = Printer::currentPositionSteps[Z_AXIS] + z;
Printer::destinationSteps[E_AXIS] = Printer::currentPositionSteps[E_AXIS] + e;
Printer::feedrate = feedrate;
#if NONLINEAR_SYSTEM
queueDeltaMove(checkEndstop,false,false);
#else
queueCartesianMove(checkEndstop,false);
#endif
Printer::feedrate = savedFeedrate;
Printer::updateCurrentPosition();
if(waitEnd)
Commands::waitUntilEndOfAllMoves();
}
#if !NONLINEAR_SYSTEM
/**
Put a move to the current destination coordinates into the movement cache.
If the cache is full, the method will wait, until a place gets free. During
wait communication and temperature control is enabled.
@param check_endstops Read endstop during move.
*/
void PrintLine::queueCartesianMove(uint8_t check_endstops,uint8_t pathOptimize)
{
Printer::unsetAllSteppersDisabled();
waitForXFreeLines(1);
uint8_t newPath=insertWaitMovesIfNeeded(pathOptimize, 0);
PrintLine *p = getNextWriteLine();
float axis_diff[4]; // Axis movement in mm
if(check_endstops) p->flags = FLAG_CHECK_ENDSTOPS;
else p->flags = 0;
p->joinFlags = 0;
if(!pathOptimize) p->setEndSpeedFixed(true);
p->dir = 0;
Printer::constrainDestinationCoords();
//Find direction
for(uint8_t axis=0; axis < 4; axis++)
{
if((p->delta[axis]=Printer::destinationSteps[axis]-Printer::currentPositionSteps[axis])>=0)
p->setPositiveDirectionForAxis(axis);
else
p->delta[axis] = -p->delta[axis];
if(axis == E_AXIS && Printer::extrudeMultiply!=100)
p->delta[E_AXIS] = (long)((p->delta[E_AXIS] * (float)Printer::extrudeMultiply) * 0.01f);
axis_diff[axis] = p->delta[axis] * Printer::invAxisStepsPerMM[axis];
if(p->delta[axis]) p->setMoveOfAxis(axis);
Printer::currentPositionSteps[axis] = Printer::destinationSteps[axis];
}
if(p->isNoMove())
{
if(newPath) // need to delete dummy elements, otherwise commands can get locked.
resetPathPlanner();
return; // No steps included
}
Printer::filamentPrinted += axis_diff[E_AXIS];
float xydist2;
#if ENABLE_BACKLASH_COMPENSATION
if((p->isXYZMove()) && ((p->dir & 7)^(Printer::backlashDir & 7)) & (Printer::backlashDir >> 3)) // We need to compensate backlash, add a move
{
waitForXFreeLines(2);
uint8_t wpos2 = linesWritePos+1;
if(wpos2>=MOVE_CACHE_SIZE) wpos2 = 0;
PrintLine *p2 = &lines[wpos2];
memcpy(p2,p,sizeof(PrintLine)); // Move current data to p2
uint8_t changed = (p->dir & 7)^(Printer::backlashDir & 7);
float back_diff[4]; // Axis movement in mm
back_diff[E_AXIS] = 0;
back_diff[X_AXIS] = (changed & 1 ? (p->isXPositiveMove() ? Printer::backlashX : -Printer::backlashX) : 0);
back_diff[Y_AXIS] = (changed & 2 ? (p->isYPositiveMove() ? Printer::backlashY : -Printer::backlashY) : 0);
back_diff[Z_AXIS] = (changed & 4 ? (p->isZPositiveMove() ? Printer::backlashZ : -Printer::backlashZ) : 0);
p->dir &=7; // x,y and z are already correct
for(uint8_t i=0; i < 4; i++)
{
float f = back_diff[i]*Printer::axisStepsPerMM[i];
p->delta[i] = abs((long)f);
if(p->delta[i]) p->dir |= 16<<i;
}
//Define variables that are needed for the Bresenham algorithm. Please note that Z is not currently included in the Bresenham algorithm.
if(p->delta[Y_AXIS] > p->delta[X_AXIS] && p->delta[Y_AXIS] > p->delta[Z_AXIS]) p->primaryAxis = Y_AXIS;
else if (p->delta[X_AXIS] > p->delta[Z_AXIS] ) p->primaryAxis = X_AXIS;
else p->primaryAxis = Z_AXIS;
p->stepsRemaining = p->delta[p->primaryAxis];
//Feedrate calc based on XYZ travel distance
xydist2 = back_diff[X_AXIS] * back_diff[X_AXIS] + back_diff[Y_AXIS] * back_diff[Y_AXIS];
if(p->isZMove())
p->distance = sqrt(xydist2 + back_diff[Z_AXIS] * back_diff[Z_AXIS]);
else
p->distance = sqrt(xydist2);
Printer::backlashDir = (Printer::backlashDir & 56) | (p2->dir & 7);
p->calculateMove(back_diff,pathOptimize);
p = p2; // use saved instance for the real move
}
#endif
//Define variables that are needed for the Bresenham algorithm. Please note that Z is not currently included in the Bresenham algorithm.
if(p->delta[Y_AXIS] > p->delta[X_AXIS] && p->delta[Y_AXIS] > p->delta[Z_AXIS] && p->delta[Y_AXIS] > p->delta[E_AXIS]) p->primaryAxis = Y_AXIS;
else if (p->delta[X_AXIS] > p->delta[Z_AXIS] && p->delta[X_AXIS] > p->delta[E_AXIS]) p->primaryAxis = X_AXIS;
else if (p->delta[Z_AXIS] > p->delta[E_AXIS]) p->primaryAxis = Z_AXIS;
else p->primaryAxis = E_AXIS;
p->stepsRemaining = p->delta[p->primaryAxis];
if(p->isXYZMove())
{
xydist2 = axis_diff[X_AXIS] * axis_diff[X_AXIS] + axis_diff[Y_AXIS] * axis_diff[Y_AXIS];
if(p->isZMove())
p->distance = RMath::max((float)sqrt(xydist2 + axis_diff[Z_AXIS] * axis_diff[Z_AXIS]),fabs(axis_diff[E_AXIS]));
else
p->distance = RMath::max((float)sqrt(xydist2),fabs(axis_diff[E_AXIS]));
}
else
p->distance = fabs(axis_diff[E_AXIS]);
p->calculateMove(axis_diff,pathOptimize);
}
#endif
void PrintLine::calculateMove(float axis_diff[],uint8_t pathOptimize)
{
#if NONLINEAR_SYSTEM
long axisInterval[5]; // shortest interval possible for that axis
#else
long axisInterval[4];
#endif
float timeForMove = (float)(F_CPU)*distance / (isXOrYMove() ? RMath::max(Printer::minimumSpeed,Printer::feedrate): Printer::feedrate); // time is in ticks
bool critical=false;
if(linesCount<MOVE_CACHE_LOW && timeForMove<LOW_TICKS_PER_MOVE) // Limit speed to keep cache full.
{
//OUT_P_I("L:",lines_count);
timeForMove += (3*(LOW_TICKS_PER_MOVE-timeForMove))/(linesCount+1); // Increase time if queue gets empty. Add more time if queue gets smaller.
//OUT_P_F_LN("Slow ",time_for_move);
critical=true;
}
timeInTicks = timeForMove;
UI_MEDIUM; // do check encoder
// Compute the solwest allowed interval (ticks/step), so maximum feedrate is not violated
long limitInterval = timeForMove/stepsRemaining; // until not violated by other constraints it is your target speed
if(isXMove())
{
axisInterval[X_AXIS] = fabs(axis_diff[X_AXIS])*F_CPU/(Printer::maxFeedrate[X_AXIS]*stepsRemaining); // mm*ticks/s/(mm/s*steps) = ticks/step
limitInterval = RMath::max(axisInterval[X_AXIS],limitInterval);
}
else axisInterval[X_AXIS] = 0;
if(isYMove())
{
axisInterval[Y_AXIS] = fabs(axis_diff[Y_AXIS])*F_CPU/(Printer::maxFeedrate[Y_AXIS]*stepsRemaining);
limitInterval = RMath::max(axisInterval[Y_AXIS],limitInterval);
}
else axisInterval[Y_AXIS] = 0;
if(isZMove()) // normally no move in z direction
{
axisInterval[Z_AXIS] = fabs((float)axis_diff[Z_AXIS])*(float)F_CPU/(float)(Printer::maxFeedrate[Z_AXIS]*stepsRemaining); // must prevent overflow!
limitInterval = RMath::max(axisInterval[Z_AXIS],limitInterval);
}
else axisInterval[Z_AXIS] = 0;
if(isEMove())
{
axisInterval[E_AXIS] = fabs(axis_diff[E_AXIS])*F_CPU/(Printer::maxFeedrate[E_AXIS]*stepsRemaining);
limitInterval = RMath::max(axisInterval[E_AXIS],limitInterval);
}
else axisInterval[E_AXIS] = 0;
#if NONLINEAR_SYSTEM
axisInterval[VIRTUAL_AXIS] = fabs(axis_diff[VIRTUAL_AXIS])*F_CPU/(Printer::maxFeedrate[X_AXIS]*stepsRemaining);
#endif
fullInterval = limitInterval>200 ? limitInterval : 200; // This is our target speed
// new time at full speed = limitInterval*p->stepsRemaining [ticks]
timeForMove = (float)limitInterval * (float)stepsRemaining; // for large z-distance this overflows with long computation
float inv_time_s = (float)F_CPU / timeForMove;
if(isXMove())
{
axisInterval[X_AXIS] = timeForMove / delta[X_AXIS];
speedX = axis_diff[X_AXIS] * inv_time_s;
if(isXNegativeMove()) speedX = -speedX;
}
else speedX = 0;
if(isYMove())
{
axisInterval[Y_AXIS] = timeForMove/delta[Y_AXIS];
speedY = axis_diff[Y_AXIS] * inv_time_s;
if(isYNegativeMove()) speedY = -speedY;
}
else speedY = 0;
if(isZMove())
{
axisInterval[Z_AXIS] = timeForMove/delta[Z_AXIS];
speedZ = axis_diff[Z_AXIS] * inv_time_s;
if(isZNegativeMove()) speedZ = -speedZ;
}
else speedZ = 0;
if(isEMove())
{
axisInterval[E_AXIS] = timeForMove/delta[E_AXIS];
speedE = axis_diff[E_AXIS] * inv_time_s;
if(isENegativeMove()) speedE = -speedE;
}
#if NONLINEAR_SYSTEM
axisInterval[VIRTUAL_AXIS] = limitInterval; //timeForMove/stepsRemaining;
#endif
fullSpeed = distance * inv_time_s;
//long interval = axis_interval[primary_axis]; // time for every step in ticks with full speed
//If acceleration is enabled, do some Bresenham calculations depending on which axis will lead it.
#ifdef RAMP_ACCELERATION
// slowest time to accelerate from v0 to limitInterval determines used acceleration
// t = (v_end-v_start)/a
float slowest_axis_plateau_time_repro = 1e15; // repro to reduce division Unit: 1/s
unsigned long *accel = (isEPositiveMove() ? Printer::maxPrintAccelerationStepsPerSquareSecond : Printer::maxTravelAccelerationStepsPerSquareSecond);
for(uint8_t i=0; i < 4 ; i++)
{
if(isMoveOfAxis(i))
// v = a * t => t = v/a = F_CPU/(c*a) => 1/t = c*a/F_CPU
slowest_axis_plateau_time_repro = RMath::min(slowest_axis_plateau_time_repro,(float)axisInterval[i] * (float)accel[i]); // steps/s^2 * step/tick Ticks/s^2
}
// Errors for delta move are initialized in timer (except extruder)
#if !NONLINEAR_SYSTEM
error[0] = error[1] = error[2] = delta[primaryAxis] >> 1;
#endif
#if NONLINEAR_SYSTEM
error[E_AXIS] = stepsRemaining >> 1;
#endif
invFullSpeed = 1.0/fullSpeed;
accelerationPrim = slowest_axis_plateau_time_repro / axisInterval[primaryAxis]; // a = v/t = F_CPU/(c*t): Steps/s^2
//Now we can calculate the new primary axis acceleration, so that the slowest axis max acceleration is not violated
fAcceleration = 262144.0*(float)accelerationPrim/F_CPU; // will overflow without float!
accelerationDistance2 = 2.0*distance*slowest_axis_plateau_time_repro*fullSpeed/((float)F_CPU); // mm^2/s^2
startSpeed = endSpeed = minSpeed = safeSpeed();
// Can accelerate to full speed within the line
if (startSpeed * startSpeed + accelerationDistance2 >= fullSpeed * fullSpeed)
setNominalMove();
vMax = F_CPU / fullInterval; // maximum steps per second, we can reach
// if(p->vMax>46000) // gets overflow in N computation
// p->vMax = 46000;
//p->plateauN = (p->vMax*p->vMax/p->accelerationPrim)>>1;
#ifdef USE_ADVANCE
if(!isXYZMove() || !isEMove())
{
#ifdef ENABLE_QUADRATIC_ADVANCE
advanceRate = 0; // No head move or E move only or sucking filament back
advanceFull = 0;
#endif
advanceL = 0;
}
else
{
float advlin = fabs(speedE)*Extruder::current->advanceL*0.001*Printer::axisStepsPerMM[E_AXIS];
advanceL = (uint16_t)((65536*advlin)/vMax); //advanceLscaled = (65536*vE*k2)/vMax
#ifdef ENABLE_QUADRATIC_ADVANCE;
advanceFull = 65536*Extruder::current->advanceK * speedE * speedE; // Steps*65536 at full speed
long steps = (HAL::U16SquaredToU32(vMax))/(accelerationPrim<<1); // v^2/(2*a) = steps needed to accelerate from 0-vMax
advanceRate = advanceFull/steps;
if((advanceFull>>16)>maxadv)
{
maxadv = (advanceFull>>16);
maxadvspeed = fabs(speedE);
}
#endif
if(advlin>maxadv2)
{
maxadv2 = advlin;
maxadvspeed = fabs(speedE);
}
}
#endif
UI_MEDIUM; // do check encoder
updateTrapezoids();
// how much steps on primary axis do we need to reach target feedrate
//p->plateauSteps = (long) (((float)p->acceleration *0.5f / slowest_axis_plateau_time_repro + p->vMin) *1.01f/slowest_axis_plateau_time_repro);
#else
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
advanceRate = 0; // No advance for constant speeds
advanceFull = 0;
#endif
#endif
#endif
// Correct integers for fixed point math used in bresenham_step
if(fullInterval<MAX_HALFSTEP_INTERVAL || critical)
halfStep = 4;
else
{
halfStep = 1;
#if NONLINEAR_SYSTEM
// Error 0-2 are used for the towers and set up in the timer
error[E_AXIS] = stepsRemaining;
#else
error[X_AXIS] = error[Y_AXIS] = error[Z_AXIS] = error[E_AXIS] = delta[primaryAxis];
#endif
}
#ifdef DEBUG_STEPCOUNT
// Set in delta move calculation
#if !NONLINEAR_SYSTEM
totalStepsRemaining = delta[X_AXIS]+delta[Y_AXIS]+delta[Z_AXIS];
#endif
#endif
#ifdef DEBUG_QUEUE_MOVE
if(Printer::debugEcho())
{
logLine();
Com::printFLN(Com::tDBGLimitInterval, limitInterval);
Com::printFLN(Com::tDBGMoveDistance, distance);
Com::printFLN(Com::tDBGCommandedFeedrate, Printer::feedrate);
Com::printFLN(Com::tDBGConstFullSpeedMoveTime, timeForMove);
}
#endif
// Make result permanent
if (pathOptimize) waitRelax = 70;
pushLine();
DEBUG_MEMORY;
}
/**
This is the path planner.
It goes from the last entry and tries to increase the end speed of previous moves in a fashion that the maximum jerk
is never exceeded. If a segment with reached maximum speed is met, the planner stops. Everything left from this
is already optimal from previous updates.
The first 2 entries in the queue are not checked. The first is the one that is already in print and the following will likely become active.
The method is called before lines_count is increased!
*/
void PrintLine::updateTrapezoids()
{
uint8_t first = linesWritePos;
PrintLine *firstLine;
PrintLine *act = &lines[linesWritePos];
BEGIN_INTERRUPT_PROTECTED;
uint8_t maxfirst = linesPos; // first non fixed segment
if(maxfirst != linesWritePos)
nextPlannerIndex(maxfirst); // don't touch the line printing
// Now ignore enough segments to gain enough time for path planning
long timeleft = 0;
// Skip as many stored moves as needed to gain enough time for computation
while(timeleft < 4500 * MOVE_CACHE_SIZE && maxfirst != linesWritePos)
{
timeleft += lines[maxfirst].timeInTicks;
nextPlannerIndex(maxfirst);
}
// Search last fixed element
while(first != maxfirst && !lines[first].isEndSpeedFixed())
previousPlannerIndex(first);
if(first != linesWritePos && lines[first].isEndSpeedFixed())
nextPlannerIndex(first);
if(first == linesWritePos) // Nothing to plan
{
act->block();
ESCAPE_INTERRUPT_PROTECTED
act->setStartSpeedFixed(true);
act->updateStepsParameter();
act->unblock();
return;
}
// now we have at least one additional move for optimization
// that is not a wait move
// First is now the new element or the first element with non fixed end speed.
// anyhow, the start speed of first is fixed
firstLine = &lines[first];
firstLine->block(); // don't let printer touch this or following segments during update
END_INTERRUPT_PROTECTED;
uint8_t previousIndex = linesWritePos;
previousPlannerIndex(previousIndex);
PrintLine *previous = &lines[previousIndex];
#if DRIVE_SYSTEM != 3
// filters z-move<->not z-move
if((previous->primaryAxis == Z_AXIS && act->primaryAxis != Z_AXIS) || (previous->primaryAxis != Z_AXIS && act->primaryAxis == Z_AXIS))
{
previous->setEndSpeedFixed(true);
act->setStartSpeedFixed(true);
act->updateStepsParameter();
firstLine->unblock();
return;
}
#endif // DRIVE_SYSTEM
computeMaxJunctionSpeed(previous,act); // Set maximum junction speed if we have a real move before
if(previous->isEOnlyMove() != act->isEOnlyMove())
{
previous->setEndSpeedFixed(true);
act->setStartSpeedFixed(true);
act->updateStepsParameter();
firstLine->unblock();
return;
}
backwardPlanner(linesWritePos,first);
// Reduce speed to reachable speeds
forwardPlanner(first);
// Update precomputed data
do
{
lines[first].updateStepsParameter();
BEGIN_INTERRUPT_PROTECTED;
lines[first].unblock(); // Flying block to release next used segment as early as possible
nextPlannerIndex(first);
lines[first].block();
END_INTERRUPT_PROTECTED;
}
while(first!=linesWritePos);
act->updateStepsParameter();
act->unblock();
}
inline void PrintLine::computeMaxJunctionSpeed(PrintLine *previous,PrintLine *current)
{
#ifdef USE_ADVANCE
if(Printer::isAdvanceActivated())
{
if(previous->isEMove() != current->isEMove() && (previous->isXOrYMove() || current->isXOrYMove()))
{
previous->setEndSpeedFixed(true);
current->setStartSpeedFixed(true);
previous->endSpeed = current->startSpeed = previous->maxJunctionSpeed = RMath::min(previous->endSpeed,current->startSpeed);
previous->invalidateParameter();
current->invalidateParameter();
return;
}
}
#endif // USE_ADVANCE
#if NONLINEAR_SYSTEM
if (previous->moveID == current->moveID) // Avoid computing junction speed for split delta lines
{
if(previous->fullSpeed>current->fullSpeed)
previous->maxJunctionSpeed = current->fullSpeed;
else
previous->maxJunctionSpeed = previous->fullSpeed;
return;
}
#endif
// First we compute the normalized jerk for speed 1
float dx = current->speedX-previous->speedX;
float dy = current->speedY-previous->speedY;
float factor=1;
#if (DRIVE_SYSTEM == 3) // No point computing Z Jerk separately for delta moves
float dz = current->speedZ-previous->speedZ;
float jerk = sqrt(dx*dx+dy*dy+dz*dz);
#else
float jerk = sqrt(dx*dx+dy*dy);
#endif
if(jerk>Printer::maxJerk)
factor = Printer::maxJerk/jerk;
#if DRIVE_SYSTEM!=3
if((previous->dir | current->dir) & 64)
{
float dz = fabs(current->speedZ-previous->speedZ);
if(dz>Printer::maxZJerk)
factor = RMath::min(factor,Printer::maxZJerk/dz);
}
#endif
float eJerk = fabs(current->speedE-previous->speedE);
if(eJerk > Extruder::current->maxStartFeedrate)
factor = RMath::min(factor,Extruder::current->maxStartFeedrate/eJerk);
previous->maxJunctionSpeed = RMath::min(previous->fullSpeed*factor,current->fullSpeed);
#ifdef DEBUG_QUEUE_MOVE
if(Printer::debugEcho()) {
Com::printF(PSTR("ID:"),(int)previous);
Com::printFLN(PSTR(" MJ:"),previous->maxJunctionSpeed);
}
#endif // DEBUG_QUEUE_MOVE
}
/** Update parameter used by updateTrapezoids
Computes the acceleration/decelleration steps and advanced parameter associated.
*/
void PrintLine::updateStepsParameter()
{
if(areParameterUpToDate() || isWarmUp()) return;
float startFactor = startSpeed * invFullSpeed;
float endFactor = endSpeed * invFullSpeed;
vStart = vMax * startFactor; //starting speed
vEnd = vMax * endFactor;
unsigned long vmax2 = HAL::U16SquaredToU32(vMax);
accelSteps = ((vmax2 - HAL::U16SquaredToU32(vStart)) / (accelerationPrim<<1)) + 1; // Always add 1 for missing precision
decelSteps = ((vmax2 - HAL::U16SquaredToU32(vEnd)) /(accelerationPrim<<1)) + 1;
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
advanceStart = (float)advanceFull*startFactor * startFactor;
advanceEnd = (float)advanceFull*endFactor * endFactor;
#endif
#endif
if(accelSteps+decelSteps >= stepsRemaining) // can't reach limit speed
{
unsigned int red = (accelSteps+decelSteps + 2 - stepsRemaining) >> 1;
accelSteps = accelSteps-RMath::min(accelSteps,red);
decelSteps = decelSteps-RMath::min(decelSteps,red);
}
setParameterUpToDate();
#ifdef DEBUG_QUEUE_MOVE
if(Printer::debugEcho())
{
Com::printFLN(Com::tDBGId,(int)this);
Com::printF(Com::tDBGVStartEnd,(long)vStart);
Com::printFLN(Com::tSlash,(long)vEnd);
Com::printF(Com::tDBAccelSteps,(long)accelSteps);
Com::printF(Com::tSlash,(long)decelSteps);
Com::printFLN(Com::tSlash,(long)stepsRemaining);
Com::printF(Com::tDBGStartEndSpeed,startSpeed,1);
Com::printFLN(Com::tSlash,endSpeed,1);
Com::printFLN(Com::tDBGFlags,flags);
Com::printFLN(Com::tDBGJoinFlags,joinFlags);
}
#endif
}
/**
Compute the maximum speed from the last entered move.
The backwards planner traverses the moves from last to first looking at deceleration. The RHS of the accelerate/decelerate ramp.
start = last line inserted
last = last element until we check
*/
inline void PrintLine::backwardPlanner(uint8_t start,uint8_t last)
{
PrintLine *act = &lines[start],*previous;
float lastJunctionSpeed = act->endSpeed; // Start always with safe speed
//PREVIOUS_PLANNER_INDEX(last); // Last element is already fixed in start speed
while(start != last)
{
previousPlannerIndex(start);
previous = &lines[start];
// Avoid speed calc once crusing in split delta move
#if NONLINEAR_SYSTEM
if (previous->moveID == act->moveID && lastJunctionSpeed == previous->maxJunctionSpeed)
{
act->startSpeed = RMath::max(act->minSpeed,previous->endSpeed = lastJunctionSpeed);
previous->invalidateParameter();
act->invalidateParameter();
}
#endif
/* if(prev->isEndSpeedFixed()) // Nothing to update from here on, happens when path optimize disabled
{
act->setStartSpeedFixed(true);
return;
}*/
// Avoid speed calcs if we know we can accelerate within the line
lastJunctionSpeed = (act->isNominalMove() ? act->fullSpeed : sqrt(lastJunctionSpeed*lastJunctionSpeed+act->accelerationDistance2)); // acceleration is acceleration*distance*2! What can be reached if we try?
// If that speed is more that the maximum junction speed allowed then ...
if(lastJunctionSpeed >= previous->maxJunctionSpeed) // Limit is reached
{
// If the previous line's end speed has not been updated to maximum speed then do it now
if(previous->endSpeed != previous->maxJunctionSpeed)
{
previous->invalidateParameter(); // Needs recomputation
previous->endSpeed = RMath::max(previous->minSpeed,previous->maxJunctionSpeed); // possibly unneeded???
}
// If actual line start speed has not been updated to maximum speed then do it now
if(act->startSpeed != previous->maxJunctionSpeed)
{
act->startSpeed = RMath::max(act->minSpeed,previous->maxJunctionSpeed); // possibly unneeded???
act->invalidateParameter();
}
lastJunctionSpeed = previous->endSpeed;
}
else
{
// Block prev end and act start as calculated speed and recalculate plateau speeds (which could move the speed higher again)
act->startSpeed = RMath::max(act->minSpeed,lastJunctionSpeed);
lastJunctionSpeed = previous->endSpeed = RMath::max(lastJunctionSpeed,previous->minSpeed);
previous->invalidateParameter();
act->invalidateParameter();
}
act = previous;
} // while loop
}
void PrintLine::forwardPlanner(uint8_t first)
{
PrintLine *act;
PrintLine *next = &lines[first];
float vmaxRight;
float leftSpeed = next->startSpeed;
while(first != linesWritePos) // All except last segment, which has fixed end speed
{
act = next;
nextPlannerIndex(first);
next = &lines[first];
/* if(act->isEndSpeedFixed())
{
leftSpeed = act->endSpeed;
continue; // Nothing to do here
}*/
// Avoid speed calc once crusing in split delta move
#if NONLINEAR_SYSTEM
if (act->moveID == next->moveID && act->endSpeed == act->maxJunctionSpeed)
{
act->startSpeed = leftSpeed;
leftSpeed = act->endSpeed;
act->setEndSpeedFixed(true);
next->setStartSpeedFixed(true);
continue;
}
#endif
// Avoid speed calcs if we know we can accelerate within the line.
vmaxRight = (act->isNominalMove() ? act->fullSpeed : sqrt(leftSpeed * leftSpeed + act->accelerationDistance2));
if(vmaxRight > act->endSpeed) // Could be higher next run?
{
if(leftSpeed < act->minSpeed) {
leftSpeed = act->minSpeed;
act->endSpeed = sqrt(leftSpeed * leftSpeed + act->accelerationDistance2);
}
act->startSpeed = leftSpeed;
next->startSpeed = leftSpeed = RMath::max(RMath::min(act->endSpeed,act->maxJunctionSpeed),next->minSpeed);
if(act->endSpeed == act->maxJunctionSpeed) // Full speed reached, don't compute again!
{
act->setEndSpeedFixed(true);
next->setStartSpeedFixed(true);
}
act->invalidateParameter();
}
else // We can accelerate full speed without reaching limit, which is as fast as possible. Fix it!
{
act->fixStartAndEndSpeed();
act->invalidateParameter();
if(act->minSpeed > leftSpeed) {
leftSpeed = act->minSpeed;
vmaxRight = sqrt(leftSpeed * leftSpeed + act->accelerationDistance2);
}
act->startSpeed = leftSpeed;
act->endSpeed = RMath::max(act->minSpeed,vmaxRight);
next->startSpeed = leftSpeed = RMath::max(RMath::min(act->endSpeed,act->maxJunctionSpeed),next->minSpeed);
next->setStartSpeedFixed(true);
}
} // While
next->startSpeed = RMath::max(next->minSpeed,leftSpeed); // This is the new segment, which is updated anyway, no extra flag needed.
}
inline float PrintLine::safeSpeed()
{
float safe(Printer::maxJerk * 0.5);
#if DRIVE_SYSTEM != 3
if(isZMove())
{
if(primaryAxis == Z_AXIS) {
safe = Printer::maxZJerk*0.5*fullSpeed/fabs(speedZ);
} else if(fabs(speedZ) > Printer::maxZJerk * 0.5)
safe = RMath::min(safe,Printer::maxZJerk * 0.5 * fullSpeed / fabs(speedZ));
}
#endif
if(isEMove())
{
if(isXYZMove())
safe = RMath::min(safe,0.5*Extruder::current->maxStartFeedrate*fullSpeed/fabs(speedE));
else
safe = 0.5*Extruder::current->maxStartFeedrate; // This is a retraction move
}
if(primaryAxis == X_AXIS || primaryAxis == Y_AXIS) // enforce minimum speed for numerical stability of explicit speed integration
safe = RMath::max(Printer::minimumSpeed,safe);
else if(primaryAxis == Z_AXIS) {
safe = RMath::max(Printer::minimumZSpeed,safe);
}
return RMath::min(safe,fullSpeed);
}
/** Check if move is new. If it is insert some dummy moves to allow the path optimizer to work since it does
not act on the first two moves in the queue. The stepper timer will spot these moves and leave some time for
processing.
*/
uint8_t PrintLine::insertWaitMovesIfNeeded(uint8_t pathOptimize, uint8_t waitExtraLines)
{
if(linesCount==0 && waitRelax==0 && pathOptimize) // First line after some time - warmup needed
{
uint8_t w = 3;
while(w--)
{
PrintLine *p = getNextWriteLine();
p->flags = FLAG_WARMUP;
p->joinFlags = FLAG_JOIN_STEPPARAMS_COMPUTED | FLAG_JOIN_END_FIXED | FLAG_JOIN_START_FIXED;
p->dir = 0;
p->setWaitForXLinesFilled(w + waitExtraLines);
p->setWaitTicks(10000*(unsigned int)w);
pushLine();
}
return 1;
}
return 0;
}
void PrintLine::logLine()
{
#ifdef DEBUG_QUEUE_MOVE
Com::printFLN(Com::tDBGId,(int)this);
Com::printArrayFLN(Com::tDBGDelta,delta);
Com::printFLN(Com::tDBGDir,dir);
Com::printFLN(Com::tDBGFlags,flags);
Com::printFLN(Com::tDBGFullSpeed,fullSpeed);
Com::printFLN(Com::tDBGVMax,(long)vMax);
Com::printFLN(Com::tDBGAcceleration,accelerationDistance2);
Com::printFLN(Com::tDBGAccelerationPrim,(long)accelerationPrim);
Com::printFLN(Com::tDBGRemainingSteps,stepsRemaining);
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
Com::printFLN(Com::tDBGAdvanceFull,advanceFull>>16);
Com::printFLN(Com::tDBGAdvanceRate,advanceRate);
#endif
#endif
#endif // DEBUG_QUEUE_MOVE
}
void PrintLine::waitForXFreeLines(uint8_t b)
{
while(linesCount+b>MOVE_CACHE_SIZE) // wait for a free entry in movement cache
{
GCode::readFromSerial();
Commands::checkForPeriodicalActions();
}
}
#if DRIVE_SYSTEM==3
/**
Calculate the delta tower position from a cartesian position
@param cartesianPosSteps Array containing cartesian coordinates.
@param deltaPosSteps Result array with tower coordinates.
@returns 1 if cartesian coordinates have a valid delta tower position 0 if not.
*/
uint8_t transformCartesianStepsToDeltaSteps(long cartesianPosSteps[], long deltaPosSteps[])
{
if(Printer::isLargeMachine())
{
float temp = Printer::deltaAPosYSteps - cartesianPosSteps[Y_AXIS];
float opt = Printer::deltaDiagonalStepsSquaredF - temp*temp;
float temp2 = Printer::deltaAPosXSteps - cartesianPosSteps[X_AXIS];
if ((temp = opt - temp2*temp2) >= 0)
deltaPosSteps[X_AXIS] = sqrt(temp) + cartesianPosSteps[Z_AXIS];
else
return 0;
temp = Printer::deltaBPosYSteps - cartesianPosSteps[Y_AXIS];
opt = Printer::deltaDiagonalStepsSquaredF - temp*temp;
temp2 = Printer::deltaBPosXSteps - cartesianPosSteps[X_AXIS];
if ((temp = opt - temp2*temp2) >= 0)
deltaPosSteps[Y_AXIS] = sqrt(temp) + cartesianPosSteps[Z_AXIS];
else
return 0;
temp = Printer::deltaCPosYSteps - cartesianPosSteps[Y_AXIS];
opt = Printer::deltaDiagonalStepsSquaredF - temp*temp;
temp2 = Printer::deltaCPosXSteps - cartesianPosSteps[X_AXIS];
if ((temp = opt - temp2*temp2) >= 0)
deltaPosSteps[Z_AXIS] = sqrt(temp) + cartesianPosSteps[Z_AXIS];
else
return 0;
return 1;
}
else
{
long temp = Printer::deltaAPosYSteps - cartesianPosSteps[Y_AXIS];
long opt = Printer::deltaDiagonalStepsSquared - temp*temp;
long temp2 = Printer::deltaAPosXSteps - cartesianPosSteps[X_AXIS];
if ((temp = opt - temp2*temp2) >= 0)
#ifdef FAST_INTEGER_SQRT
deltaPosSteps[X_AXIS] = HAL::integerSqrt(temp) + cartesianPosSteps[Z_AXIS];
#else
deltaPosSteps[X_AXIS] = sqrt(temp) + cartesianPosSteps[Z_AXIS];
#endif
else
return 0;
temp = Printer::deltaBPosYSteps - cartesianPosSteps[Y_AXIS];
opt = Printer::deltaDiagonalStepsSquared - temp*temp;
temp2 = Printer::deltaBPosXSteps - cartesianPosSteps[X_AXIS];
if ((temp = opt - temp2*temp2) >= 0)
#ifdef FAST_INTEGER_SQRT
deltaPosSteps[Y_AXIS] = HAL::integerSqrt(temp) + cartesianPosSteps[Z_AXIS];
#else
deltaPosSteps[Y_AXIS] = sqrt(temp) + cartesianPosSteps[Z_AXIS];
#endif
else
return 0;
temp = Printer::deltaCPosYSteps - cartesianPosSteps[Y_AXIS];
opt = Printer::deltaDiagonalStepsSquared - temp*temp;
temp2 = Printer::deltaCPosXSteps - cartesianPosSteps[X_AXIS];
if ((temp = opt - temp2*temp2) >= 0)
#ifdef FAST_INTEGER_SQRT
deltaPosSteps[Z_AXIS] = HAL::integerSqrt(temp) + cartesianPosSteps[Z_AXIS];
#else
deltaPosSteps[Z_AXIS] = sqrt(temp) + cartesianPosSteps[Z_AXIS];
#endif
else
return 0;
}
return 1;
}
#endif
#if DRIVE_SYSTEM==4
/**
Calculate the delta tower position from a cartesian position
@param cartesianPosSteps Array containing cartesian coordinates.
@param deltaPosSteps Result array with tower coordinates.
@returns 1 if cartesian coordinates have a valid delta tower position 0 if not.
X Y
* *
\ /
\ /
\ /
\/
/
/
/
/
* Extruder
*/
uint8_t transformCartesianStepsToDeltaSteps(long cartesianPosSteps[], long tugaPosSteps[])
{
tugaPosSteps[0] = cartesianPosSteps[0];
tugaPosSteps[2] = cartesianPosSteps[2];
long y2 = Printer::deltaBPosXSteps-cartesianPosSteps[1];
if(Printer::isLargeMachine())
{
float y2f = (float)y2*(float)y2;
float temp = Printer::deltaDiagonalStepsSquaredF - y2f;
if(temp<0) return 0;
tugaPosSteps[1] = tugaPosSteps[0] + sqrt(temp);
}
else
{
y2 = y2*y2;
long temp = Printer::deltaDiagonalStepsSquared - y2;
if(temp<0) return 0;
tugaPosSteps[1] = tugaPosSteps[0] + HAL::integerSqrt(temp);
}
return 1;
}
#endif
#if NONLINEAR_SYSTEM
void DeltaSegment::checkEndstops(PrintLine *cur,bool checkall)
{
if(Printer::isZProbingActive())
{
#if FEATURE_Z_PROBE
if(isZNegativeMove() && Printer::isZProbeHit())
{
cur->setXMoveFinished();
cur->setYMoveFinished();
cur->setZMoveFinished();
dir = 0;
Printer::stepsRemainingAtZHit = cur->stepsRemaining;
return;
}
#endif
#if DRIVE_SYSTEM==3
if(isZPositiveMove() && isXPositiveMove() && isYPositiveMove() && (Printer::isXMaxEndstopHit() || Printer::isYMaxEndstopHit() || Printer::isZMaxEndstopHit()))
#else
if(isZPositiveMove() && Printer::isZMaxEndstopHit())
#endif
{
cur->setXMoveFinished();
cur->setYMoveFinished();
cur->setZMoveFinished();
dir = 0;
Printer::stepsRemainingAtZHit = cur->stepsRemaining;
return;
}
}
if(checkall)
{
if(isXPositiveMove() && Printer::isXMaxEndstopHit())
{
#if DRIVE_SYSTEM==3
Printer::stepsRemainingAtXHit = cur->stepsRemaining;
#endif
setXMoveFinished();
cur->setXMoveFinished();
}
if(isYPositiveMove() && Printer::isYMaxEndstopHit())
{
#if DRIVE_SYSTEM==3
Printer::stepsRemainingAtYHit = cur->stepsRemaining;
#endif
setYMoveFinished();
cur->setYMoveFinished();
}
if(isXPositiveMove() && Printer::isXMaxEndstopHit()) {
setXMoveFinished();
cur->setXMoveFinished();
}
if(isYPositiveMove() && Printer::isYMaxEndstopHit()) {
setYMoveFinished();
cur->setYMoveFinished();
}
#if DRIVE_SYSTEM!=3
if(isXNegativeMove() && Printer::isXMinEndstopHit()) {
setXMoveFinished();
cur->setXMoveFinished();
}
if(isYNegativeMove() && Printer::isYMinEndstopHit()) {
setYMoveFinished();
cur->setYMoveFinished();
}