-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathMotion.cpp
987 lines (841 loc) · 26.6 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
#include "Motion.h"
#include "config.h"
#include "GCode.h"
#include "Axis.h"
#include "Globals.h"
#include "GcodeQueue.h"
#include "ArduinoMap.h"
#include <avr/pgmspace.h>
#define max(x,y) (x > y ? x : y)
#define min(x,y) (x < y ? x : y)
// Testing shows this is probably better put nearer 1000.
#define MIN_INTERVAL 500
void Motion::setFeedModifier(float mod)
{
feed_modifier = mod/100.0f;
}
float Motion::getFeedModifier()
{
return(feed_modifier*100.0f);
}
Point& Motion::getCurrentPosition()
{
static Point p;
for(int ax=0;ax<NUM_AXES;ax++)
p[ax] = AXES[ax].getCurrentPosition();
return p;
}
void Motion::setCurrentPosition(GCode &gcode)
{
for(int ax=0;ax<NUM_AXES;ax++)
{
if(!gcode[ax].isUnused())
{
AXES[ax].setCurrentPosition(gcode[ax].getFloat());
}
}
}
void Motion::setMinimumFeedrate(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setMinimumFeedrate(gcode[ax].getFloat());
}
}
void Motion::setMaximumFeedrate(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setMaximumFeedrate(gcode[ax].getFloat());
}
}
void Motion::setAverageFeedrate(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setAverageFeedrate(gcode[ax].getFloat());
}
}
void Motion::setStepsPerUnit(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setStepsPerUnit(gcode[ax].getFloat());
}
}
void Motion::setAccel(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setAccel(gcode[ax].getFloat());
}
}
#define MOT_CHANGEPIN(FOO) \
for(int ax=0;ax < NUM_AXES;ax++) \
{ \
if(gcode[ax].isUnused()) \
continue; \
\
AXES[ax].FOO(ArduinoMap::getPort(gcode[ax].getInt()), ArduinoMap::getPinnum(gcode[ax].getInt())); \
}
void Motion::setStepPins(GCode& gcode) { MOT_CHANGEPIN(changepinStep); }
void Motion::setDirPins(GCode& gcode) { MOT_CHANGEPIN(changepinDir); }
void Motion::setEnablePins(GCode& gcode) { MOT_CHANGEPIN(changepinEnable); }
void Motion::setMinPins(GCode& gcode) { MOT_CHANGEPIN(changepinMin); }
void Motion::setMaxPins(GCode& gcode) { MOT_CHANGEPIN(changepinMax); }
void Motion::setAxisInvert(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setInvert(gcode[ax].getInt());
}
}
void Motion::setMinStopPos(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setMinStopPos(gcode[ax].getFloat());
}
}
void Motion::setMaxStopPos(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setMaxStopPos(gcode[ax].getFloat());
}
}
void Motion::setAxisDisable(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode[ax].isUnused()) continue;
AXES[ax].setDisable(gcode[ax].getInt());
}
}
void Motion::setEndstopGlobals(bool inverted, bool pulledup)
{
Axis::setPULLUPS(pulledup);
Axis::setEND_INVERT(inverted);
}
void Motion::reportConfigStatus(Host& h)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
h.labelnum("CS:", ax, false);
h.write(' ');
AXES[ax].reportConfigStatus(h);
h.endl();
}
}
void Motion::disableAllMotors()
{
for(int ax=0;ax < NUM_AXES;ax++)
AXES[ax].disable();
}
void Motion::checkdisable(GCode& gcode)
{
// This was STUPID
}
void Motion::disableAxis(int axis)
{
AXES[axis].disableIfConfigured();
}
void Motion::getMovesteps(GCode& gcode)
{
for(int ax=0;ax < NUM_AXES;ax++)
{
gcode.axismovesteps[ax] = AXES[ax].getMovesteps(gcode.startpos[ax],
gcode[ax].isUnused() ? gcode.startpos[ax] : gcode[ax].getFloat(),
gcode.axisdirs[ax]);
if(gcode.movesteps < gcode.axismovesteps[ax])
{
gcode.movesteps = gcode.axismovesteps[ax];
gcode.leading_axis = ax;
}
}
}
float Motion::getSmallestStartFeed(GCode& gcode)
{
float mi = 9999999;
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode.axismovesteps[ax] == 0) continue;
float t = AXES[ax].getStartFeed(gcode.feed);
if(t < mi) mi = t;
}
return mi;
}
float Motion::getSmallestEndFeed(GCode& gcode)
{
float mi = 9999999;
for(int ax=0;ax < NUM_AXES;ax++)
{
if(gcode.axismovesteps[ax] == 0) continue;
float t = AXES[ax].getEndFeed(gcode.feed);
if(t < mi) mi = t;
}
return mi;
}
void Motion::getActualEndpos(GCode& gcode)
{
for(int ax=0;ax<NUM_AXES;ax++)
{
gcode.endpos[ax] = AXES[ax].getEndpos(gcode.startpos[ax], gcode.axismovesteps[ax], gcode.axisdirs[ax]);
}
}
void Motion::gcode_precalc(GCode& gcode, float& feedin, Point* lastend)
{
if(gcode.state >= GCode::PREPARED)
return;
if(gcode[G].isUnused())
return;
if(gcode[G].getInt() == 92)
{
// Just carry over new position
for(int ax=0;ax<NUM_AXES;ax++)
{
if(!gcode[ax].isUnused())
{
(*lastend)[ax] = gcode[ax].getFloat();
}
}
gcode.state = GCode::PREPARED;
return;
}
if(gcode[G].getInt() != 1 and gcode[G].getInt() != 2)
{
// no precalc for anything but 92, 1, 2
gcode.state = GCode::PREPARED;
return;
}
// We want to carry over the previous ending position and feedrate if possible.
gcode.startpos = *lastend;
if(gcode[F].isUnused())
gcode.feed = feedin;
else
gcode.feed = gcode[F].getFloat();
if(gcode.feed == 0)
gcode.feed = SAFE_DEFAULT_FEED;
getMovesteps(gcode);
getActualEndpos(gcode);
*lastend = gcode.endpos;
feedin = gcode.feed;
gcode.state = GCode::PREPARED;
if(gcode.movesteps == 0)
return;
// Calculate actual distance of move along vector
gcode.actualmm = 0;
for(int ax=0;ax<NUM_AXES;ax++)
{
gcode.actualmm += pow(gcode.axismovesteps[ax]/AXES[ax].getStepsPerMM(), 2);
}
gcode.actualmm = sqrt(gcode.actualmm);
float axisspeeds[NUM_AXES];
// Calculate individual axis movement speeds
float mult = gcode.feed/gcode.actualmm;
for(int ax=0;ax<NUM_AXES;ax++)
{
axisspeeds[ax] = (gcode.axismovesteps[ax] / AXES[ax].getStepsPerMM()) * mult;
#ifdef DEBUG_LAME
HOST.labelnum("AS", ax, false);
HOST.labelnum(":", axisspeeds[ax]);
#endif
}
// Calculate ratio of movement speeds to main axis
for(int ax=0;ax < NUM_AXES;ax++)
{
if(axisspeeds[ax] != 0)
gcode.axisratio[ax] = axisspeeds[gcode.leading_axis] / axisspeeds[ax];
else
gcode.axisratio[ax] = 0;
}
// Check all axis for violation o top speed. Take the biggest violator and change
// the leading axis speed to match it.
float bigdiff = 0;
float littlediff = 0;
for(int ax = 0;ax<NUM_AXES;ax++)
{
if(axisspeeds[ax] > AXES[ax].getMaxFeed())
{
float d = (axisspeeds[ax] - AXES[ax].getMaxFeed()) * gcode.axisratio[ax];
#ifdef DEBUG_LAME
HOST.labelnum("D",ax,false);
HOST.labelnum(":",axisspeeds[ax] - AXES[ax].getMaxFeed(),false);
HOST.labelnum(" rat: ", gcode.axisratio[ax]);
#endif
if(d > bigdiff)
bigdiff = d;
}
if(axisspeeds[ax] > AXES[ax].getStartFeed()/2)
{
float d = (axisspeeds[ax] - (AXES[ax].getStartFeed()/2)) * gcode.axisratio[ax];
if(d > littlediff)
littlediff = d;
}
}
#ifdef DEBUG_LAME
HOST.labelnum("BD:", bigdiff);
HOST.labelnum("LD:", littlediff);
#endif
gcode.maxfeed = axisspeeds[gcode.leading_axis] - bigdiff;
gcode.startfeed = axisspeeds[gcode.leading_axis] - littlediff;
gcode.endfeed = gcode.startfeed;
gcode.currentfeed = gcode.startfeed;
gcode.minfeed = gcode.startfeed;
// TODO: We shoudl treat accel as we do the speeds above and scale it to fit the chosen axis.
// instead we just take the accel of the leadng axis.
float accel = AXES[gcode.leading_axis].getAccel();
gcode.accel = accel;
for(int ax=0;ax<NUM_AXES;ax++)
{
if(gcode.axismovesteps[ax])
AXES[ax].enable();
}
#ifdef DEBUG_LAME
HOST.labelnum("F1: ", gcode.startfeed);
HOST.labelnum("F2: ", gcode.maxfeed);
HOST.labelnum("Accel: ", accel);
#endif
uint32_t dist = AXES[gcode.leading_axis].getAccelDist(gcode.startfeed, gcode.maxfeed, accel);
uint32_t halfmove = gcode.movesteps >> 1;
if(halfmove <= dist)
{
gcode.accel_until = gcode.movesteps - halfmove;
gcode.decel_from = halfmove;
}
else
{
gcode.accel_until = gcode.movesteps - dist;
gcode.decel_from = dist;
}
gcode.currentinterval = AXES[gcode.leading_axis].interval_from_feedrate((float)gcode.startfeed * feed_modifier);
gcode.currentfeed = gcode.startfeed;
// TODO: this only changes when we change accel rates; can we just store it per-axis until we scale accels properly?
gcode.accel_inc = (float)((float)accel * 60.0f / ACCELS_PER_SECOND);
gcode.accel_timer = ACCEL_INC_TIME;
gcode.optimized = false;
}
// Diverent moves need to be handled specially.
// Divergent moves are ones where one axis is increasing in speed, while another is
// decreasing. This means if we blindly adjust one side, then the other, as we do,
// the second adjustment is likely to bring the first adjustment out of whack.
// So here we basically limit speed to the maximum speed from which it's impossible to go out of whack.
// TODO: Don't assume all diverence is on XY
// this algorithm is crap.
void Motion::fix_diverge(int32_t *ends, int32_t *starts)
{
int32_t dA = labs(labs(ends[0]) - labs(ends[1]));
int32_t dB = labs(labs(starts[0]) - labs(starts[1]));
// max diverge is 2x jump - diff in other axis.
// .. or something like that.
//int32_t mdiv = (AXES[0].getStartFeed() * 2) - dB;
int32_t mdiv = AXES[0].getStartFeed()*2;
if(dB < AXES[0].getStartFeed())
mdiv -= dB;
if(dA > mdiv)
{
float ar = (float)mdiv / (float)dA;
if(ar < 1)
{
for(int ax=0;ax<NUM_AXES;ax++)
{
ends[ax] = (float)ends[ax] * ar;
}
#ifdef DEBUG_LAME
HOST.labelnum("divratio: ", ar);
#endif
#ifdef DEBUG_LAME
for(int ax=0;ax<NUM_AXES;ax++)
{
HOST.labelnum("DIV:[", ax, false);
HOST.labelnum("]:", ends[ax],false);
HOST.labelnum("->", starts[ax], false);
HOST.labelnum(" @jump:", AXES[ax].getStartFeed());
}
#endif
}
}
}
// This is a routine that limits endspeed to a rate at which we can hit
// start speeds. Run it in reverse to limit the start speed to something we
// can hit from our end speed.
bool Motion::join_moves(int32_t *ends, int32_t *starts)
{
float ratio = 1;
for(int ax=0;ax<NUM_AXES;ax++)
{
float ar = 1;
// The 0.75f in the next line is the shit part; it's there because
// it helps us guarantee we're within jerk after 4 iterations (see
// unused diverge function above for explanation why) but it
// obviouly means no move that is adjusted is going to be optimum.
uint32_t jump = (float)AXES[ax].getStartFeed() * 0.75f;
uint32_t desired = fabs(starts[ax]) + jump;
if((starts[ax] == 0) != (ends[ax] == 0))
desired = jump;
else if((starts[ax] > 0) != (ends[ax] > 0))
desired = jump/2;
ar = float(desired) / fabs(ends[ax]);
if(ar < ratio)
{
ratio = ar;
}
}
if(ratio < 1)
{
for(int ax=0;ax<NUM_AXES;ax++)
{
ends[ax] = (float)ends[ax] * ratio;
}
return true;
}
return false;
}
// This is the lookahead algorithm. From a high level, we simply
// limit our end speed and the next start speed to appropriate limits,
// then further limit them to a speed where reaching a stop is possible.
void Motion::gcode_optimize(GCode& gcode, GCode& nextg)
{
#ifdef LOOKAHEAD
// THIS NEEDS SERIOUS REFACTORIN
if(gcode.optimized)
return;
gcode.optimized = true;
// If this isn't a move, we have nothing to do.
if(gcode[G].isUnused() || gcode[G].getInt() != 1 || gcode.movesteps == 0)
return;
// If the NEXT gcode isn't a move, then we will just recomute our accels
// (assuming the previous move changed them during it's optimization)
if(nextg[G].isUnused() || nextg[G].getInt() != 1 || nextg.movesteps == 0)
{
computeAccel(gcode);
return;
}
// Calculate the requested speed of each axis at its peak during this move,
// including a direction sign. TODO: We calculated this once already, maybe we can store it.
int32_t axisspeeds[NUM_AXES];
int32_t endspeeds[NUM_AXES];
int32_t nextspeeds[NUM_AXES];
int32_t startspeeds[NUM_AXES];
float mult1 = (float)gcode.maxfeed / gcode.actualmm;
float mult2 = (float)nextg.maxfeed / nextg.actualmm;
for(int ax=0;ax<NUM_AXES;ax++)
{
axisspeeds[ax] = (float)((float)gcode.axismovesteps[ax] / AXES[ax].getStepsPerMM()) * mult1;
axisspeeds[ax] *= gcode.axisdirs[ax] ? 1 : -1;
endspeeds[ax] = axisspeeds[ax];
nextspeeds[ax] = (float)((float)nextg.axismovesteps[ax] / AXES[ax].getStepsPerMM()) * mult2;
nextspeeds[ax] *= nextg.axisdirs[ax] ? 1 : -1;
startspeeds[ax] = nextspeeds[ax];
}
int32_t *ends, *starts, *temp;
ends = endspeeds;
starts = startspeeds;
// TODO this is stupid shit.
int MAX_OPTS = (float)AXES[0].getMaxFeed() / (float)AXES[0].getStartFeed();
if(MAX_OPTS < 4)
MAX_OPTS = 4;
int c;
// this algorithm is crap.
for(c=0;c<MAX_OPTS;c++)
{
// Calculate the end speeds (of this move) we can use to meet the start speeds (of the next move).
if(!join_moves(ends,starts) && c >= 1)
break;
temp = ends;
ends = starts;
starts = temp;
}
for(int ax=0;ax<NUM_AXES;ax++)
{
#ifdef DEBUG_OPT
HOST.labelnum("OPTS:",c);
HOST.labelnum("ASP[", ax, false);
HOST.labelnum("]:", axisspeeds[ax],false);
HOST.labelnum("->", endspeeds[ax],false);
HOST.labelnum(", ", startspeeds[ax],false);
HOST.labelnum("->", nextspeeds[ax], false);
HOST.labelnum(" @jump:", AXES[ax].getStartFeed());
#endif
if(labs(endspeeds[ax] - startspeeds[ax]) > AXES[ax].getStartFeed())
{
if(labs(endspeeds[ax] - startspeeds[ax]) - AXES[ax].getStartFeed() > (float)AXES[ax].getStartFeed())
{
#ifdef DEBUG_JUMP
HOST.labelnum("JUMP EXCEED LINE ", gcode.linenum);
#endif
endspeeds[gcode.leading_axis] = AXES[gcode.leading_axis].getStartFeed() / 2;
startspeeds[nextg.leading_axis] = AXES[nextg.leading_axis].getStartFeed() / 2;
}
}
}
// Speed at which the next move's leading axis can reach 0 during the next move.
float speedto0 = AXES[nextg.leading_axis].
getSpeedAtEnd(AXES[nextg.leading_axis].getStartFeed()/2,
nextg.accel,
nextg.movesteps);
// NOT TODO: startspeeds/endspeeds is signed previous to this operation but unsigned
// after. Not important, though.
// If the next move cannot reach 0, limit it so it can.
if(speedto0 < labs(startspeeds[nextg.leading_axis]))
{
#ifdef DEBUG_LAME
HOST.labelnum("st0beg:",speedto0);
HOST.labelnum("beg:",startspeeds[nextg.leading_axis]);
#endif
startspeeds[nextg.leading_axis] = speedto0;
}
// now speedto0 is the maximum speed the primary in the next move can be going. We need the equivalent speed of the primary in this move.
speedto0 = (speedto0 * gcode.axisratio[nextg.leading_axis]);
// If this move isn't moving the primary of the next move, then speedto0 will come out to 0.
// This is obviously incorrect...
if(speedto0 < labs(endspeeds[gcode.leading_axis]))
{
#ifdef DEBUG_LAME
HOST.labelnum("st0end:",speedto0);
HOST.labelnum("end:",endspeeds[gcode.leading_axis]);
#endif
endspeeds[gcode.leading_axis] = speedto0;
}
#ifdef DEBUG_LAME
HOST.labelnum("ef: ", gcode.endfeed, false);
HOST.labelnum("sf: ", gcode.startfeed, false);
#endif
gcode.endfeed = max(gcode.endfeed,labs(endspeeds[gcode.leading_axis]));
nextg.startfeed = max(nextg.startfeed,labs(startspeeds[nextg.leading_axis]));
// because we only lookahead one move, our maximum exit speed has to be either the desired
// exit speed or the speed that the next move can reach to 0 (0+jerk, actually) during.
computeAccel(gcode, &nextg);
#endif // LOOKAHEAD
}
// This computes an acceleration curve, given requested start, max, and end speeds for a move.
// Optimally, also pass the next move, and it will adjust the start speed there to match the
// actual speeds we can achieve < max.
void Motion::computeAccel(GCode& gcode, GCode* nextg)
{
if(gcode[G].isUnused() || gcode[G].getInt() != 1)
return;
if(gcode.movesteps == 0)
return;
if(gcode.startfeed < gcode.minfeed) // Optimization might have accidentally lowered us past this point.
gcode.startfeed = gcode.minfeed;
// Two cases:
// 1) start speed < end speed; we get to accelerate for free up to end.
// 2) start speed >= end speed; we must plan decel irst, then add in appropriate accel.
if(gcode.startfeed < gcode.endfeed)
{
uint32_t distance_to_end = AXES[gcode.leading_axis].getAccelDist(gcode.startfeed, gcode.endfeed, gcode.accel);
uint32_t distance_to_max = AXES[gcode.leading_axis].getAccelDist(gcode.startfeed, gcode.maxfeed, gcode.accel);
// start is less than end, and we cannot accelerate enough to make the end in time.
if(distance_to_end >= gcode.movesteps)
{
gcode.decel_from = 0;
gcode.accel_until = 0;
// TODO: fix - should be speed we will reach + jerk
gcode.endfeed = AXES[gcode.leading_axis].getSpeedAtEnd(gcode.startfeed, gcode.accel, gcode.movesteps);
if(nextg != NULL)
nextg->startfeed = gcode.endfeed / nextg->axisratio[gcode.leading_axis];
}
else // start is less than end, and we have extra room to accelerate.
{
uint32_t halfspace = (gcode.movesteps - distance_to_end)/2;
distance_to_max -= distance_to_end;
if(distance_to_max <= halfspace)
{
// Plateau
gcode.accel_until = gcode.movesteps - distance_to_end - distance_to_max;
gcode.decel_from = distance_to_max;
}
else
{
// Peak
gcode.accel_until = gcode.movesteps - distance_to_end - halfspace;
gcode.decel_from = halfspace;
}
}
}
else // start speed >= end speed... must decelrate primarily, accel if time.
{
uint32_t distance_to_end = AXES[gcode.leading_axis].getAccelDist(gcode.endfeed, gcode.startfeed, gcode.accel);
uint32_t distance_to_max = AXES[gcode.leading_axis].getAccelDist(gcode.startfeed, gcode.maxfeed, gcode.accel);
if(distance_to_end >= gcode.movesteps)
{
// TODO: this is NOT GOOD. Throw an error.
#ifdef DEBUG_ACCEL
HOST.labelnum("TOO FAST! ", gcode.movesteps, false);
HOST.labelnum(", needs ", distance_to_end, false);
HOST.labelnum(" at ", gcode.accel, false);
HOST.labelnum(" - ", gcode.startfeed, false);
HOST.labelnum(" - ", gcode.endfeed);
#endif
gcode.decel_from = gcode.movesteps;
gcode.accel_until = gcode.movesteps;
// TODO: fix - should be speed we will reach + jerk
gcode.endfeed = AXES[gcode.leading_axis].getSpeedAtEnd(gcode.startfeed, -gcode.accel, gcode.movesteps);
if(nextg != NULL)
nextg->startfeed = max(gcode.endfeed * nextg->axisratio[gcode.leading_axis], nextg->startfeed);
}
else // lots of room to decelerate
{
uint32_t halfspace = (gcode.movesteps - distance_to_end)/2;
if(distance_to_max <= halfspace)
{
// Plateau
gcode.accel_until = gcode.movesteps - distance_to_max;
gcode.decel_from = distance_to_max + distance_to_end;
}
else
{
// Peak
gcode.accel_until = gcode.movesteps - halfspace;
gcode.decel_from = halfspace + distance_to_end;
}
}
}
gcode.currentinterval = AXES[gcode.leading_axis].interval_from_feedrate((float)gcode.startfeed * feed_modifier);
gcode.currentfeed = gcode.startfeed;
if(nextg != NULL && nextg->startfeed > nextg->maxfeed)
nextg->startfeed = nextg->maxfeed;
#ifdef DEBUG_ACCEL
HOST.labelnum("lines:",gcode.linenum,false);
if(nextg != NULL)
HOST.labelnum("-",nextg->linenum,false);
HOST.labelnum(" steps:", gcode.movesteps,false);
HOST.labelnum(" au1:", gcode.accel_until,false);
HOST.labelnum(" df1:", gcode.decel_from,false);
HOST.labelnum(" attain: ", AXES[gcode.leading_axis].getSpeedAtEnd(gcode.startfeed, gcode.accel, gcode.movesteps-gcode.accel_until), false);
HOST.labelnum(" start: ", gcode.startfeed, false);
HOST.labelnum(" max: ", gcode.maxfeed, false);
HOST.labelnum(" end: ", gcode.endfeed, false);
if(nextg != NULL)
{
HOST.labelnum(" nextstart: ", nextg->startfeed, false);
HOST.labelnum(" nextmax: ", nextg->maxfeed,false);
HOST.labelnum(" nextsteps:", nextg->movesteps,false);
HOST.labelnum(" au2:", nextg->accel_until,false);
HOST.labelnum(" df2:", nextg->decel_from);
}
else
{
HOST.write(" - unopt.\n");
}
#endif
}
// Takes the next queued gcode and begins running it.
void Motion::gcode_execute(GCode& gcode)
{
// Only execute codes that are prepared.
if(gcode.state < GCode::PREPARED)
return; // TODO: This should never happen now and is an error.
// Don't execute codes that are ACTIVE or DONE (ACTIVE get handled by interrupt)
if(gcode.state > GCode::PREPARED)
return;
// Make sure they have configured the axis!
if(AXES[0].isInvalid())
{
Host::Instance(gcode.source).write_P(PSTR("!! AXIS ARE NOT CONFIGURED !!\n"));
gcode.state = GCode::DONE;
return;
}
if(gcode.movesteps == 0)
{
gcode.state = GCode::DONE;
return;
}
// Prepare axis move data -- Invalidate all precomputes if bad data (happens on hitting an endstop)
for(int ax=0;ax<NUM_AXES;ax++)
{
if(!AXES[ax].setupMove(gcode.startpos[ax], gcode.axisdirs[ax], gcode.axismovesteps[ax]))
{
GCODES.Invalidate();
// We'll get back here after the first move is recomputed.
return;
}
deltas[ax] = gcode.axismovesteps[ax];
errors[ax] = gcode.movesteps >> 1;
}
// setup pointer to current move data for interrupt
gcode.state = GCode::ACTIVE;
current_gcode = &gcode;
setInterruptCycles(gcode.currentinterval);
enableInterrupt();
}
bool Motion::axesAreMoving()
{
for(int ax=0;ax<NUM_AXES;ax++)
if(AXES[ax].isMoving()) return true;
return false;
}
void Motion::writePositionToHost(GCode& gc)
{
for(int ax=0;ax<NUM_AXES;ax++)
{
Host::Instance(gc.source).write(ax > Z ? 'A' - Z - 1 + ax : 'X' + ax);
Host::Instance(gc.source).write(':');
Host::Instance(gc.source).write(AXES[ax].getCurrentPosition(),0,2);
Host::Instance(gc.source).write(' ');
}
}
// SJFW's main movement routine in some sense; this is executed by the processor
// for each step of the primary axis in a movement.
void Motion::handleInterrupt()
{
// This shouldn't be necessary if I've managed things properly, but I doubt I have.
if(busy)
return;
#ifdef INTERRUPT_STEPS
// We typically have this option enabled to allow the comms interrupt
// to occur while we are doing anything heavy here.
busy = true;
//resetTimer();
disableInterrupt();
sei();
#endif
// interruptOverflow for step intervals > 16bit
if(interruptOverflow > 0)
{
interruptOverflow--;
enableInterrupt();
busy=false;
return;
}
if(current_gcode->movesteps == 0)
{
disableInterrupt();
current_gcode->state = GCode::DONE;
busy=false;
return;
}
current_gcode->movesteps--;
// Bresenham-style axis alignment algorithm
for(ax=0;ax<NUM_AXES;ax++)
{
if(ax == current_gcode->leading_axis)
{
AXES[ax].doStep();
continue;
}
errors[ax] = errors[ax] - deltas[ax];
if(errors[ax] < 0)
{
AXES[ax].doStep();
errors[ax] = errors[ax] + deltas[current_gcode->leading_axis];
}
}
accelsteps = 0;
current_gcode->accel_timer += current_gcode->currentinterval;
// Handle acceleration and deceleration
while(current_gcode->accel_timer > ACCEL_INC_TIME)
{
current_gcode->accel_timer -= ACCEL_INC_TIME;
accelsteps++;
}
if(accelsteps)
{
if(current_gcode->movesteps >= current_gcode->accel_until && current_gcode->currentfeed < current_gcode->maxfeed)
{
current_gcode->currentfeed += current_gcode->accel_inc * accelsteps;
if(current_gcode->currentfeed > current_gcode->maxfeed)
current_gcode->currentfeed = current_gcode->maxfeed;
current_gcode->currentinterval = AXES[current_gcode->leading_axis].interval_from_feedrate((float)(current_gcode->currentfeed) * feed_modifier);
setInterruptCycles(current_gcode->currentinterval);
}
else if(current_gcode->movesteps <= current_gcode->decel_from && current_gcode->currentfeed > current_gcode->endfeed)
{
current_gcode->currentfeed -= current_gcode->accel_inc * accelsteps;
if(current_gcode->currentfeed < current_gcode->endfeed)
current_gcode->currentfeed = current_gcode->endfeed;
current_gcode->currentinterval = AXES[current_gcode->leading_axis].interval_from_feedrate((float)(current_gcode->currentfeed) * feed_modifier);
setInterruptCycles(current_gcode->currentinterval);
}
}
// This check is only important if we hit endstops; lets us know all the involved axis
// have reached their end early.
if(!axesAreMoving())
{
current_gcode->movesteps = 0;
}
if(current_gcode->movesteps == 0)
{
disableInterrupt();
current_gcode->state = GCode::DONE;
}
#ifdef INTERRUPT_STEPS
else
enableInterrupt();
busy = false;
#endif
}
void Motion::setupInterrupt()
{
// 16-bit registers that must be set/read with interrupts disabled:
// TCNTn, OCRnA/B/C, ICRn
// "CTC" and no prescaler.
//TCCR1A = 0;
//TCCR1B = _BV(WGM12) | _BV(CS10);
// "Fast PWM", top = OCR1A
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
TCCR1A = _BV(WGM11) | _BV(WGM10);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
// Clear flag
TIFR1 &= ~(_BV(OCF1A));
// Enable timer
PRR0 &= ~(_BV(PRTIM1));
// Outcompare Compare match A interrupt
TIMSK1 &= ~(_BV(OCIE1A));
// Clear flag
TIFR1 &= ~(_BV(OCF1A));
}
}
void Motion::resetTimer()
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
// Disabel timer
PRR0 |= _BV(PRTIM1);
// unSET flag
TIFR1 &= ~(_BV(OCF1A));
// Reset Timer
TCNT1=0;
}
}
void Motion::enableInterrupt()
{
// Outcompare Compare match A interrupt
TIMSK1 |= _BV(OCIE1A);
}
void Motion::disableInterrupt()
{
// Outcompare Compare match A interrupt
TIMSK1 &= ~(_BV(OCIE1A));
}
// With a 16-bit timer operating at 1:1 with the clock,
// we have to verflow at 0xFFFF, thus the 60000 check below.
void Motion::setInterruptCycles(unsigned long cycles)
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
if(cycles > 60000)
{
OCR1A = 60000;
interruptOverflow = cycles / 60000;
}
else if(cycles < MIN_INTERVAL)
OCR1A = MIN_INTERVAL;
else
OCR1A = cycles;
}
}
ISR(TIMER1_COMPA_vect)
{
MOTION.handleInterrupt();
}