Repository navigation
Expand file tree
/
Copy pathFastAccelStepper.h
More file actions
1029 lines (960 loc) · 46.8 KB
/
Copy pathFastAccelStepper.h
File metadata and controls
1029 lines (960 loc) · 46.8 KB
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
#ifndef FASTACCELSTEPPER_H
#define FASTACCELSTEPPER_H
#include <stdint.h>
#include "fas_arch/common.h"
#include "FastAccelStepperEngine.h"
enum class ExtDirPendingState : uint8_t { None = 0xff, Low = 0, High = 1 };
class FastAccelStepper;
// ### Return codes of calls to `move()` and `moveTo()`
//
// The defined preprocessor macros are MOVE_xxx:
// MOVE_OK: All is OK:
// MOVE_ERR_NO_DIRECTION_PIN: Negative direction requested, but no direction pin
// MOVE_ERR_SPEED_IS_UNDEFINED: The maximum speed has not been set yet
// MOVE_ERR_ACCELERATION_IS_UNDEFINED: The acceleration to use has not been set
// yet
// ### Return codes of `rampState()`
//
// The return value is an uint8_t, which consist of two fields:
//
// | Bit 7 | Bits 6-5 | Bits 4-0 |
// |:--------|:----------|:---------|
// |Always 0 | Direction | State |
//
// The bit mask for direction and state:
#define RAMP_DIRECTION_MASK (32 + 64)
#define RAMP_STATE_MASK (1 + 2 + 4 + 8 + 16)
// The defined ramp states are:
#define RAMP_STATE_IDLE 0
#define RAMP_STATE_COAST 1
#define RAMP_STATE_ACCELERATE 2
#define RAMP_STATE_DECELERATE 4
#define RAMP_STATE_REVERSE (4 + 8)
#define RAMP_STATE_ACCELERATING_FLAG 2
#define RAMP_STATE_DECELERATING_FLAG 4
// And the two directions of a move
#define RAMP_DIRECTION_COUNT_UP 32
#define RAMP_DIRECTION_COUNT_DOWN 64
// A ramp state value of 2 is set after any move call on a stopped motor
// and until the stepper task is serviced. The stepper task will then
// control the direction flags
#include "fas_ramp/RampGenerator.h"
//
// ## Timing values - Architecture dependent
//
// ### AVR
// |VARIABLE | Value | Unit |
// |:----------------|------------:|:------------------------|
// |TICKS_PER_S | 16_000_000 | [ticks/s] |
// |MIN_CMD_TICKS | 640 | [1/TICKS_PER_S seconds] |
// |MIN_DIR_DELAY_US | 40 | [µs] |
// |MAX_DIR_DELAY_US | 4095 | [µs] |
//
// ### ESP32
// |VARIABLE | Value | Unit |
// |:----------------|------------:|:------------------------|
// |TICKS_PER_S | 16_000_000 | [ticks/s] |
// |MIN_CMD_TICKS | 3200 | [1/TICKS_PER_S seconds] |
// |MIN_DIR_DELAY_US | 200 | [µs] |
// |MAX_DIR_DELAY_US | 4095 | [µs] |
//
// ### SAM DUE
// |VARIABLE | Value | Unit |
// |:----------------|------------:|:------------------------|
// |TICKS_PER_S | 21_000_000 | [ticks/s] |
// |MIN_CMD_TICKS | 4200 | [1/TICKS_PER_S seconds] |
// |MIN_DIR_DELAY_US | 200 | [µs] |
// |MAX_DIR_DELAY_US | 3120 | [µs] |
//
// # FastAccelStepper
#define MAX_ON_DELAY_TICKS ((uint32_t)(65535 * (QUEUE_LEN - 1)))
#define PIN_UNDEFINED 255
#define PIN_EXTERNAL_FLAG 128
// Is this pin number an I2S mux slot rather than a GPIO?
//
// The low five bits are the slot and PIN_I2S_FLAG marks it, so a mux slot is
// `0x40 | slot` -- 64 and up, which is not a pin on any ESP32. Callers that
// would otherwise hand such a value to the GPIO driver have to ask this first:
// the flag is *kept* on a mux direction/enable pin (the queue needs it to find
// the bit in the frame), so stripping it on the way in would lose the slot.
// Every platform without I2S answers false, so the call sites need no #if.
//
// Off ESP32 there is no PIN_I2S_FLAG at all, so nothing can be a mux slot.
static inline bool isI2sMuxPin(uint8_t pin) {
#if defined(PIN_I2S_FLAG)
return (pin & PIN_I2S_FLAG) != 0;
#else
(void)pin;
return false;
#endif
}
class FastAccelStepper {
#ifdef TEST
public:
#else
private:
#endif
void init(FastAccelStepperEngine* engine, uint8_t num, uint8_t step_pin);
public:
// ## Step Pin
// step pin is defined at creation. Here can retrieve the pin
uint8_t getStepPin() const;
// ## Direction Pin
// if direction pin is connected, call this function.
//
// If the pin number is >= 128, then the direction pin is assumed to be
// external and the external callback function (set by
// `setExternalCallForPin()`) is used to set the pin. For direction pin, this
// is implemented for esp32 and its supported derivates, and avr and its
// derivates except atmega32u4
//
// For slow driver hardware the first step after any polarity change of the
// direction pin can be delayed by the value dir_change_delay_us. The allowed
// range is MIN_DIR_DELAY_US and MAX_DIR_DELAY_US. The special value of 0
// means, that no delay is added. Values 1 up to MIN_DIR_DELAY_US will be
// clamped to MIN_DIR_DELAY_US. Values above MAX_DIR_DELAY_US will be clamped
// to MAX_DIR_DELAY_US. For external pins, dir_change_delay_us is ignored,
// because the mechanism applied for external pins provides already pause
// in the range of ms or more.
//
// ESP32 I2S_DIRECT requires a GPIO (or external pin >= 128). I2S mux slots
// (`pin | PIN_I2S_FLAG`) are valid only with I2S_MUX.
//
// ESP32 MCPWM/PCNT inserts one MIN_CMD_TICKS pause (old DIR) before a
// direction change. apply_command() runs at MCPWM compare (tick 1, TEA),
// when STEP has just gone high; STEP stays high until TEP. The pause
// defers the DIR toggle to TEA of that pause, with STEP already low
// (#370). Independent of dir_change_delay_us.
//
// ESP-IDF 5+ also latches generator actions at TEZ/TEP (one-command
// pipeline). startQueue applies the first command with immediate update
// so leftover utea=2 cannot pulse during a leading pause.
void setDirectionPin(uint8_t dirPin, bool dirHighCountsUp = true,
uint16_t dir_change_delay_us = 0);
inline uint8_t getDirectionPin() const { return _dirPin; }
inline bool directionPinHighCountsUp() const { return _dirHighCountsUp; }
// Ticks of the pause to issue *before* a direction change (old DIR), for
// pipeline drain (RMT/I2S/MCPWM). 0 means none, so it is also the pause
// count: one pause of this length, or none. Coordinated n-axis planners
// should emit it on every axis, not wait for inject.
uint16_t getDirChangeBeforeTicks() const;
// Ticks of the pause that carries the new DIR: max of the user
// `dir_change_delay_us` from `setDirectionPin()` and the driver's
// after-delay. External DIR pins return 2 ms. 0 means none.
uint16_t getDirChangeAfterTicks() const;
// ## Enable Pin
// if enable pin is connected, then use this function.
//
// If the pin number is >= 128, then the enable pin is assumed to be
// external and the external callback function (set by
// `setExternalCallForPin()`) is used to set the pin.
//
// In case there are two enable pins: one low and one high active, then
// these calls are valid and both pins will be operated:
// setEnablePin(pin1, true);
// setEnablePin(pin2, false);
// If pin1 and pin2 are same, then the last call will be used.
void setEnablePin(uint8_t enablePin, bool low_active_enables_stepper = true);
inline uint8_t getEnablePinHighActive() const { return _enablePinHighActive; }
inline uint8_t getEnablePinLowActive() const { return _enablePinLowActive; }
// using enableOutputs/disableOutputs the stepper can be enabled and disabled
// For a running motor with autoEnable set, disableOutputs() will return false
bool enableOutputs(); // returns true, if enabled
bool disableOutputs(); // returns true, if disabled
// In auto enable mode, the stepper is enabled before stepping and disabled
// afterwards. The delay from stepper enabled till first step and from
// last step to stepper disabled can be separately adjusted.
//
// setDelayToEnable() sets the delay from enable to first step.
// Return values:
// - DelayResultCode::OK: Delay accepted
// - DelayResultCode::TOO_LOW: Delay is 0 (minimum is 1µs)
// - DelayResultCode::TOO_HIGH: Delay exceeds MAX_ON_DELAY_TICKS
// (~120ms ESP32, ~60ms AVR @ 16MHz)
//
// setDelayToDisable() sets the delay from last step to disable.
// This is executed in the periodic stepper task (~4-10ms rate) and thus
// has several ms of jitter.
void setAutoEnable(bool auto_enable);
DelayResultCode setDelayToEnable(uint32_t delay_us);
void setDelayToDisable(uint16_t delay_ms);
// ## Stepper Position
// Retrieve the current position of the stepper.
//
// While a move is running, this value leads the step pin. The driver
// accepts steps into its pipeline before those pulses are emitted. At
// high speed the lead is large: on ESP32 RMT one step can be a single
// symbol, and a full symbol block plus the next chunk can already be
// committed. getCurrentPosition() does not estimate how far that
// pipeline has played out.
//
// If the pulses that have already left the pin are what matters,
// attach a pulse counter and use readPulseCounter(). Counters 6 and 7
// are not used by the stepper drivers.
int32_t getCurrentPosition() const;
// Set the current position of the stepper - either in standstill or while
// moving.
// for esp32: the implementation uses getCurrentPosition(), which does not
// consider the steps of the current command
// => recommend to use only in standstill
void setCurrentPosition(int32_t new_pos);
// ## Stepper running status
// is true while the stepper is running or ramp generation is active
bool isRunning() const;
// ## Speed
// For stepper movement control by FastAccelStepper's ramp generator
//
// Speed can be defined in four different units:
// - In Hz: This means steps/s
// - In millHz: This means in steps/1000s
// - In us: This means in us/step
//
// For the device's maximum allowed speed, the following calls can be used.
uint16_t getMaxSpeedInUs() const;
uint16_t getMaxSpeedInTicks() const;
uint32_t getMaxSpeedInHz() const;
uint32_t getMaxSpeedInMilliHz() const;
// For esp32 and avr, the device's maximum allowed speed can be overridden.
// Allocating a new stepper will override any absolute speed limit.
// This is absolutely untested, no error checking implemented.
// Use at your own risk !
#if defined(SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING)
void setAbsoluteSpeedLimit(uint16_t max_speed_in_ticks);
#endif
// Setting the speed can be done with the four `setSpeed...()` calls.
// The new value will be used only after call of these functions:
//
// - `move()`
// - `moveTo()`
// - `runForward()`
// - `runBackward()`
// - `applySpeedAcceleration()`
// - `moveByAcceleration()`
//
// Note: no update on `stopMove()`
//
// Returns 0 on success, or -1 on invalid value.
// Invalid is faster than MaxSpeed or slower than ~250 Mio ticks/step.
int8_t setSpeedInUs(uint32_t min_step_us);
int8_t setSpeedInTicks(uint32_t min_step_ticks);
int8_t setSpeedInHz(uint32_t speed_hz);
int8_t setSpeedInMilliHz(uint32_t speed_mhz);
// To retrieve current set speed. This means, while accelerating and/or
// decelerating, this is NOT the actual speed !
inline uint32_t getSpeedInUs() const { return _rg.getSpeedInUs(); }
inline uint32_t getSpeedInTicks() const { return _rg.getSpeedInTicks(); }
inline uint32_t getSpeedInMilliHz() const { return _rg.getSpeedInMilliHz(); }
// If the current speed is needed, then use `getCurrentSpeed...()`. This
// retrieves the actual speed.
//
// | value | description |
// |:-----:|:-----------------------------|
// | = 0 | while not moving |
// | > 0 | while position counting up |
// | < 0 | while position counting down |
//
// If the parameter realtime is true, then the most actual speed
// from the stepper queue is derived. This works only, if the queue
// does not contain pauses, which is normally the case for slow speeds.
// Otherwise the speed from the ramp generator is reported, which is
// done always in case of `realtime == false`. That speed is typically
// the value of the speed a couple of milliseconds later.
//
// The drawback of `realtime == true` is, that the reported speed
// may either come from the queue or from the ramp generator.
// This means the returned speed may have jumps during
// acceleration/deceleration.
//
// For backward compatibility, the default is true.
int32_t getCurrentSpeedInUs(bool realtime = true) const;
int32_t getCurrentSpeedInMilliHz(bool realtime = true) const;
// ## Acceleration
// setAcceleration() expects as parameter the change of speed
// as step/s².
// If for example the speed should ramp up from 0 to 10000 steps/s within
// 10s, then the acceleration is 10000 steps/s / 10s = 1000 steps/s²
//
// New value will be used after call to
// move/moveTo/runForward/runBackward/applySpeedAcceleration/moveByAcceleration
//
// note: no update on stopMove()
//
// Returns 0 on success, or -1 on invalid value (<=0)
inline int8_t setAcceleration(int32_t step_s_s) {
return _rg.setAcceleration(step_s_s);
}
inline uint32_t getAcceleration() const { return _rg.getAcceleration(); }
// getCurrentAcceleration() retrieves the actual acceleration.
// = 0 while idle or coasting
// > 0 while speed is changing towards positive values
// < 0 while speed is changing towards negative values
inline int32_t getCurrentAcceleration() const {
return _rg.getCurrentAcceleration();
}
// ## Linear Acceleration
// setLinearAcceleration expects as parameter the number of steps,
// where the acceleration is increased linearly from standstill up to the
// configured acceleration value. If this parameter is 0, then there will be
// no linear acceleration phase
//
// If for example the acceleration should ramp up from 0 to 10000 steps/s^2
// within 100 steps, then call setLinearAcceleration(100)
//
// The speed at which linear acceleration turns into constant acceleration
// can be calculated from the parameter linear_acceleration_steps.
// Let's call this parameter `s_h` for handover steps.
// Then the speed is:
// `v_h = sqrt(1.5 * a * s_h)`
//
// New value will be used after call to
// move/moveTo/runForward/runBackward/applySpeedAcceleration/moveByAcceleration
//
// note: no update on stopMove()
inline void setLinearAcceleration(uint32_t linear_acceleration_steps) {
_rg.setLinearAcceleration(linear_acceleration_steps);
}
// ## Jump Start
// setJumpStart expects as parameter the ramp step to start from standstill.
//
// The speed at which the stepper will start can be calculated like this:
// - If linear acceleration is not in use:
// start speed `v = sqrt(2 * a * jump_step)`
// - If linear acceleration is in use and `jump_step <= s_h`:
// start speed `v = sqrt(1.5*a)/s_h^(1/6) * jump_step^(2/3)`
// - If linear acceleration is in use and `jump_step > s_h`:
// start speed `v = sqrt(2 * a * (jump_step - s_h/4))`
//
//
// New value will be used after call to
// move/moveTo/runForward/runBackward
inline void setJumpStart(uint32_t jump_step) { _rg.setJumpStart(jump_step); }
// ## Apply new speed/acceleration value
// This function applies new values for speed/acceleration.
// This is convenient especially, if the stepper is set to continuous running.
void applySpeedAcceleration();
// ## Move commands
// ### move() and moveTo()
// start/move the stepper for (move) steps or to an absolute position.
//
// If the stepper is already running, then the current running move will be
// updated together with any updated values of acceleration/speed. The move is
// relative to the target position of any ongoing move ! If the new
// move/moveTo for an ongoing command would reverse the direction, then the
// command is silently ignored.
// return values are the MOVE_... constants
MoveResultCode move(int32_t move, bool blocking = false);
MoveResultCode moveTo(int32_t position, bool blocking = false);
// ### keepRunning()
// This command flags the stepper to keep run continuously into current
// direction. It can be stopped by stopMove.
// Be aware, if the motor is currently decelerating towards reversed
// direction, then keepRunning() will speed up again and not finish direction
// reversal first.
void keepRunning();
bool isRunningContinuously() const { return _rg.isRunningContinuously(); }
// ### runForward() and runBackwards()
// These commands just let the motor run continuously in one direction.
// If the motor is running in the opposite direction, it will reverse
// return value as with move/moveTo
MoveResultCode runForward();
MoveResultCode runBackward();
// ### forwardStep() and backwardStep()
// forwardStep()/backwardstep() can be called, while stepper is not moving
// If stepper is moving, this is a no-op.
// backwardStep() is a no-op, if no direction pin defined
// It will immediately let the stepper perform one single step.
// If blocking = true, then the routine will wait till isRunning() is false
void forwardStep(bool blocking = false);
void backwardStep(bool blocking = false);
// ### moveByAcceleration()
// moveByAcceleration() can be called, if only the speed of the stepper
// is of interest and that speed to be controlled by acceleration.
// The maximum speed (in both directions) to be set by setSpeedInUs() before.
// The behaviour will be:
// acceleration > 0 => accelerate towards positive maximum speed
// acceleration = 0 => keep current speed
// acceleration < 0
// => accelerate towards negative maximum speed if allow_reverse
// => decelerate towards motor stop if allow_reverse = false
// return value as with move/moveTo
MoveResultCode moveByAcceleration(int32_t acceleration,
bool allow_reverse = true);
// ### stopMove()
// Stop the running stepper with normal deceleration.
// This only sets a flag and can be called from an interrupt !
void stopMove();
inline bool isStopping() const { return _rg.isStopping(); }
// ### stepsToStop()
// This returns the current step value of the ramp.
// This equals the number of steps for a motor to
// reach the current position and speed from standstill
// and to come to standstill with deceleration if stopped
// immediately.
// This value is valid with or without linear acceleration
// being used.
// Primary use is to forecast possible stop position.
// The stop position is:
// getCurrentPosition() + stepsToStop()
// in case of a motor running in positive direction.
uint32_t stepsToStop() const { return _rg.stepsToStop(); }
// ### forceStop()
// Abruptly stop the running stepper without deceleration.
// This can be called from an interrupt !
//
// The stepper command queue will be processed, but no further commands are
// added. This means, that the stepper can be expected to stop within approx.
// 20ms.
void forceStop();
// abruptly stop the running stepper without deceleration.
// This can be called from an interrupt !
//
// No further step will be issued. As this is aborting all commands in the
// queue, the actual stop position is lost (recovering this position cannot be
// done within an interrupt). So the new position after stop has to be
// provided and will be set as current position after stop.
void forceStopAndNewPosition(int32_t new_pos);
// Return the cause of the last stop and clear it. For a planner that shares
// the queue with the ramp API: it polls this to notice that a member axis
// was stopped manually (stopMove) or abruptly (forceStop /
// forceStopAndNewPosition) and then aborts the coordinated plan.
StepperStopCause takeStopCause();
StepperStopCause getStopCause() const {
return (StepperStopCause)_stop_cause;
}
// ### resumeCommands()
// Rearm the queue after forceStop() or forceStopAndNewPosition().
//
// Both stops set a queue admission latch: addQueueEntry() then refuses every
// command with AQE_ERROR_COMMANDS_SUSPENDED, including
// addQueueEntry(NULL, start). The latch is a backstop against a planner whose
// own stop flag is wrong, so it stays set until a caller explicitly rearms.
//
// This is the public key to it, and it is required by the low-level
// addQueueEntry() API: without it, a caller that aborted cannot queue again
// on the same connection. The high-level API needs no call -- the ramp clears
// the latch itself on the next fill_queue() pass.
//
// Note this does not resume motion. After forceStopAndNewPosition() the queue
// was emptied and the position was overwritten, so the caller owns the
// coordinate from here (see setCurrentPosition()).
//
// Not for clearing a stop mid-flight: to abort, use forceStop() or
// forceStopAndNewPosition().
void resumeCommands();
// True while commands are refused. See resumeCommands().
bool areCommandsSuspended() const;
// get the target position for the current move.
// As of now, this position is the view of the stepper task.
// This means, the value will stay unchanged after a move/moveTo until the
// stepper task is executed.
// In keep running mode, the targetPos() is not updated
inline int32_t targetPos() const { return _rg.targetPosition(); }
// ### Task planning
// The stepper task adds commands to the stepper queue until
// either at least two commands are planned, or the commands
// cover sufficient time into the future. Default value for that time is 20ms.
//
// The stepper task is cyclically executed every ~4ms.
// Especially for avr, the step interrupts puts a significant load on the uC,
// so the cyclical stepper task can even run for 2-3 ms. On top of that,
// other interrupts caused by the application could increase the load even
// further.
//
// Consequently, the forward planning should fill the queue for ideally two
// cycles, this means 8ms. This means, the default 20ms provide a sufficient
// margin and even a missed cycle is not an issue.
//
// The drawback of the 20ms is, that any change in speed/acceleration are
// added after those 20ms and for an application, requiring fast reaction
// times, this may impact the expected performance.
//
// Due to this the forward planning time can be adjusted with the following
// API call for each stepper individually.
//
// ### Driver in-flight (read-ahead) contract
// `fill_queue()` fills the queue to `_forward_planning_in_ticks` (default
// 20 ms), and while a move is running the queue MUST NOT run low. A pulse
// driver, though, drains commands out of the queue into its own hardware
// pipeline "in flight" ahead of the pin, so the queue only needs to keep
// commands for *that* pipeline fed. The contract is therefore:
//
// forward_planning_ticks > driver's maximum in-flight time
//
// Otherwise the driver can drain the whole queue mid-move, find it empty
// and stop/under-run. Each driver must state how much it will drain at
// most (in flight):
// - AVR / SAM / SAMD / Teensy / Pico: no buffered pipeline; at most one
// command at a time is consumed, so in-flight is one command.
// - ESP32 I2S: the DMA blocks, I2S_BLOCK_COUNT*I2S_BLOCK_TICKS = 1 ms.
// - ESP32 MCPWM/PCNT: generator actions latch at TEZ/TEP, so the timer
// holds about one command in its shadow/active registers plus the
// period being generated; in-flight is ~one command.
// - ESP32 RMT (IDF4): the half filler ping-pongs one PART_SIZE-symbol
// half per threshold; the RMT memory holds two halves, so in-flight is
// the playback time of 2*PART_SIZE symbols (bounded by the command
// periods, which the fill routine limits).
// - ESP32 RMT (IDF5/6): rmt_encode_fill() caps every RMT sub-entry (the
// step high and every low chunk) at RMT_MAX_SYMBOL_TICKS
// (= RMT_BLOCK_TICKS/(2*PART_SIZE)). A symbol holds TWO sub-entries, so a
// symbol is at most 2*RMT_MAX_SYMBOL_TICKS and one RMT half
// (PART_SIZE symbols) spans at most RMT_BLOCK_TICKS = 8000 ticks =
// 0.5 ms. The channel's mem_block_symbols = 2*PART_SIZE buffer therefore
// holds at most RMT_BUFFER_TICKS = 16000 ticks = 1 ms, and that is the
// driver's in-flight. The direction-change drain must exceed it, because
// the DIR toggle is executed while encoding, not while playing: see
// esp32_before_pause_ticks(). See
// extras/doc/implemented/040_idf6_rmt_slow.md.
//
// Attention:
// - This is only for advanced users: no error checking is implemented.
// - Only change the forward planning time, if the stepper is not running.
// - It must stay above the used driver's maximum in-flight time, otherwise
// the queue can drain mid-move.
// - Too small values bear the risk of a stepper running at full speed
// suddenly stopping
// due to lack of commands in the queue.
inline void setForwardPlanningTimeInMs(uint8_t ms) {
_forward_planning_in_ticks = ms;
_forward_planning_in_ticks *= TICKS_PER_S / 1000; // ticks per ms
}
// ## Intermediate Level Stepper Control for Advanced Users
//
// The main purpose is to bypass the ramp generator as mentioned in
// [#299](https://github.com/gin66/FastAccelStepper/issues/299).
// This shall allow to run consecutive small moves with fixed speed.
// The parameters are steps (which can be 0) and duration in ticks.
// steps=0 makes sense in order to keep the time running and not
// getting out of sync.
// Due to integer arithmetics the actual duration may be off by a small value.
// That's why the actual_duration in TICKS is returned.
// The application should consider this for the next runTimed move.
//
// The optional parameter is a boolean called start. This allows for the first
// invocation to not start the queue yet. This is for managing steppers in
// parallel. It allows to fill all steppers' queues and then kick it off by a
// call to `moveTimed(0,0,NULL,true)`. Successive invocations can keep true.
//
// In order to not have another lightweight ramp generator running in
// background interrupt, the expecation to the application is, that this
// function is frequently enough called without the queue being emptied.
//
// The current implementation immediately starts with a step, if there should
// be one. Perhaps performing the step in the middle of the duration is more
// appropriate ?
//
// A pause (steps = 0, duration > 0) uses the last queued direction, XOR
// prepare_revert (default false). So a normal pause does not toggle DIR;
// moveTimed(0, dt, ..., true) is a pause in the opposite direction.
//
// A move that changes direction makes the queue driver inject a pause command
// (see "Capacity and direction-change pauses" below). These pauses extend the
// time the move takes and they consume queue slots. If a pause is injected,
// moveTimed() returns AQE_DIR_CHANGE_PAUSE_INJECTED or
// AQE_DIR_PIN_2MS_PAUSE_ADDED and the command was NOT enqueued; in this case
// *actual_duration carries the ticks of the one injected pause. The
// application accumulates this value per retry (e.g. an "extra" variable) and
// computes the drift only after the move is accepted. The application has to
// account for the pauses - e.g. when scheduling the next timed move or when
// deciding that a stepper has finished - in order to not get out of sync with
// the stepper timing. Coordinated multi-axis motion can issue a
// prepare_revert pause on the reversing axis and the same duration as a
// normal pause on the others.
//
// Recommended retry pattern:
// uint32_t actual = 0, extra = 0;
// for (;;) {
// rc = stepper.moveTimed(steps, duration, &actual);
// if (rc == DirChangePauseInjected || rc == DirPin2msPauseAdded) {
// extra += actual;
// continue;
// }
// if (rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY) {
// drift = (int32_t)(duration - (actual + extra));
// break;
// }
// ... other retry codes unchanged ...
// }
//
// ### MoveTimedResultCode - Return codes for moveTimed()
//
// This enum extends AqeResultCode with additional codes:
//
// Positive values (retry later):
// - MOVE_TIMED_BUSY (7): Queue too full to append this timed move
// - MOVE_TIMED_EMPTY (8): Queue ran empty, but move was appended
// - AQE_DIR_CHANGE_PAUSE_INJECTED (6): Direction-change pause injected, the
// move command was NOT enqueued. *actual_duration holds the injected pause
// ticks. Accumulate and retry the same move.
// - AQE_DIR_PIN_2MS_PAUSE_ADDED (5): 2ms pause for an external direction pin
// inserted, the move command was NOT enqueued. *actual_duration holds the
// injected pause ticks. Accumulate and retry the same move.
// - (plus AQE_QUEUE_FULL, AQE_DIR_PIN_IS_BUSY,
// AQE_WAIT_FOR_ENABLE_PIN_ACTIVE, AQE_DEVICE_NOT_READY from
// AqeResultCode)
//
// Zero:
// - MOVE_TIMED_OK (0): Move successfully appended
//
// Negative values (errors):
// - MOVE_TIMED_TOO_LARGE_ERROR (-4): Move exceeds queue capacity.
// Queue depth is 32 (ESP32/SAM) or 16 (AVR). Each entry emits max 255
// steps. For slow speeds (>65535 ticks/step), pauses are needed, reducing
// capacity. Recommendation: keep duration in the range of milliseconds.
//
// ### Capacity and direction-change pauses
//
// A direction change makes the queue driver inject pause commands on top of
// the step command itself: buffered drivers (ESP32 RMT, I2S) first drain
// their output pipeline so no step in the old direction is emitted after the
// change, and every driver enforces a configured direction-pin delay with a
// pause command that carries the change. At most one pause is injected per
// addQueueEntry()/moveTimed() call; the total number over the course of a
// move is driver dependent (e.g. the ESP32 RMT driver needs up to three
// pauses across retries). moveTimed() therefore reserves two extra slots up
// front and only admits a move when the whole move plus the reserved slots
// fits into the queue at once (atomic append). Otherwise it returns
// MOVE_TIMED_BUSY instead of silently dropping steps mid-append (see
// Issue 370).
//
// As a consequence a single move may use at most QUEUE_LEN - 2 queue
// entries. For streaming at fixed speed it is recommended to keep the number
// of queue commands a move generates well below QUEUE_LEN/2 and to split
// larger moves on the application side, so the reserved slots never block a
// steady feed.
// - (plus AQE_ERROR_TICKS_TOO_LOW, AQE_ERROR_EMPTY_QUEUE_TO_START,
// AQE_ERROR_NO_DIR_PIN_TO_TOGGLE from AqeResultCode)
MoveTimedResultCode moveTimed(int16_t steps, uint32_t duration,
uint32_t* actual_duration, bool start = true,
bool prepare_revert = false);
// ## Low Level Stepper Queue Management (low level access)
//
// This interface bypasses the ramp generator and writes raw commands into
// the per-stepper queue. It gives full control over position, speed and
// direction, but the application is responsible for the ramp. It is meant
// for applications doing their own motion planning, e.g. a G-code
// interpreter.
//
// The high level interface always ends a move at speed ~0 at the target
// position and does not expose the exact position/speed/acceleration
// relation while running. To chain segments without stopping in between,
// this low level interface (or a planner built on it) is required.
//
// For coordinated multi-axis motion prefer the planners that sit on top of
// this interface: FasNAxis (polyline, as fast as possible) and FasTimed
// (constant speed for a given duration). They use the queues below and
// complement the raw interface, so they should be the first choice unless
// fully custom commands are needed.
//
// To stay tick-exact, the queue must not run empty and interrupts must be
// serviced in time. Do not block interrupts for long. On esp32, do not write
// to flash while a stepper is running (e.g. an OTA update): motion continues
// but is noticeably bumpy.
//
// If the queue is already running, then the start parameter is obsolete.
// But the queue may run out of commands while executing addQueueEntry,
// so it is better to set start=true to automatically restart/continue
// a running queue.
//
// If the queue is not running, then the start parameter defines starting it
// or not. The latter case is of interest to first fill the queue and then
// start it.
//
// The call addQueueEntry(NULL, true) just starts the queue. A synchronized
// start of several steppers is the single engine operation
// FastAccelStepperEngine::synchronizedStart(), which releases the listed
// queues in one engine operation. The per-stepper call should still return
// very fast, too, in case the queue is full and not started.
// ### Direction Change Delay Enforcement
//
// If the new command's direction differs from the previous command,
// addQueueEntry() will automatically insert pause commands to ensure
// sufficient delay before the first step in the new direction:
//
// - For external direction pins (pin >= 128): The direction pin is controlled
// via an external callback (e.g., to an I/O expander). To avoid steps in
// the wrong direction, the queue must be empty of steps before the
// direction change. If steps are present or the external callback is still
// pending, a 2ms pause is inserted and AQE_DIR_PIN_2MS_PAUSE_ADDED is
// returned. The caller should retry until the queue drains and the callback
// completes.
//
// - For regular direction pins: If a pause is required (a configured
// dir_change_delay_us > 0 and/or the driver needs to drain its output
// pipeline before the change), one or more pause commands are queued and
// AQE_DIR_CHANGE_PAUSE_INJECTED is returned WITHOUT enqueueing the
// submitted command. The caller must retry (the same as for
// AQE_DIR_PIN_2MS_PAUSE_ADDED); moveTimed() and the internal queue fill
// do so automatically. On the retry the direction already matches, or the
// pauses are skipped, and the command is enqueued.
//
// ESP32 I2S GPIO DIR is async at fill time, so both DMA blocks must be
// pause (2*I2S_BLOCK_TICKS before the change). I2S mux-slot DIR is valid
// only with I2S_MUX and needs I2S_BLOCK_TICKS after the change (the mask
// applies to the next buffer). I2S_DIRECT direction pins are GPIO.
//
// - For autoEnable mode: The enable-on delay is extended to at least
// dir_change_delay_ticks if a direction change occurs.
//
// ### stepper_command_s structure
//
// This structure defines a low-level stepper motor command for
// addQueueEntry():
//
// - `ticks`: Number of ticks between each step. Must be >=
// getMaxSpeedInTicks().
// There are TICKS_PER_S ticks per second (platform dependent).
//
// - `steps`: Number of steps to send. If 0, this is a pause command lasting
// for `ticks` ticks.
//
// - `count_up`: Direction. True = direction pin HIGH, False = direction pin
// LOW.
//
// Constraint: `ticks * steps` must be >= MIN_CMD_TICKS.
//
// Example: ticks=TICKS_PER_S/1000, steps=3, count_up=true means:
// 1. Direction pin set to HIGH
// 2. One step is generated
// 3. Exactly 1ms after the first step, the second step
// 4. Exactly 1ms after the second step, the third step
// 5. The stepper waits for 1ms
// 6. The next command is processed
//
// A command with steps=N and ticks=T occupies N*T ticks: N steps spaced T
// apart, plus a trailing wait of T after the last step. The next command
// then starts right after that, so its first step is T ticks after the last
// step of the previous command.
//
// ### Slow step rates and the uint16_t ticks limit
//
// `ticks` is a uint16_t, so the longest gap between two steps is 65535
// ticks (~4.1ms at 16MHz). Slower stepping is done by inserting pause
// commands (steps = 0) between steps, because the queue time is the sum of
// all commands. Example: 3 steps every 10ms at TICKS_PER_S=16MHz:
//
// - ticks=40000, steps=1, count_up=true (first step)
// - ticks=40000, steps=0, count_up=true (pause)
// - ticks=40000, steps=0, count_up=true (pause)
// - ticks=40000, steps=0, count_up=true (pause)
// - ticks=40000, steps=1, count_up=true (second step)
// - ... and so on for the third step
//
// The 16 bit limit is deliberate: the esp32 pulse generator registers are
// 16 bit and this keeps AVR and esp32 on the same code path. The queue holds
// only ~10ms of commands, so the application can react to position, speed
// and acceleration changes almost instantly; wider tick values would only
// make the driver slower.
//
// ### AqeResultCode - Return codes for addQueueEntry()
//
// Positive values indicate the caller should retry later:
// - AQE_OK (0): Command added successfully
// - AQE_QUEUE_FULL (1): Queue is full, retry later
// - AQE_DIR_PIN_IS_BUSY (2): Direction pin is busy, retry later
// - AQE_WAIT_FOR_ENABLE_PIN_ACTIVE (3): Waiting for enable delay, retry later
// - AQE_DEVICE_NOT_READY (4): Device not ready, retry later
// - AQE_DIR_PIN_2MS_PAUSE_ADDED (5): 2ms pause queued for an external dir
// pin; retry until the callback completes
// - AQE_DIR_CHANGE_PAUSE_INJECTED (6): dir-change pause(s) queued; retry to
// enqueue the submitted command
//
// Negative values indicate errors (do not retry):
// - AQE_ERROR_TICKS_TOO_LOW (-1): the command is too fast to be
// queued. Two separate checks, and the second is the one that surprises:
// ticks must be >= getMaxSpeedInTicks(), AND the command's total duration
// must be >= MIN_CMD_TICKS (200us, i.e. TICKS_PER_S / 5000). The duration
// is ticks * steps for a multi-step command, so a command of `steps` steps
// at period `ticks` is accepted when ticks * steps >= MIN_CMD_TICKS. A
// pause (steps == 0) and a single-step command have duration == ticks, so
// for those two the period itself must clear MIN_CMD_TICKS: a single step
// cannot be queued faster than 200us, however fast the driver is.
// Consequence: getMaxSpeedInTicks() is the fastest *period*, not the
// fastest value that can appear as `ticks` on its own. To run at that
// period, put enough steps in the command to reach MIN_CMD_TICKS.
// - AQE_ERROR_EMPTY_QUEUE_TO_START (-2): Empty command with start=true, but
// queue empty
// - AQE_ERROR_NO_DIR_PIN_TO_TOGGLE (-3): count_up=false without direction pin
//
// ### aqeRetry() / aqeRetryImmediately() / aqeIsOk() - helpers for
// AqeResultCode
//
// aqeRetry(code) returns true for all positive codes, i.e. every code that
// indicates the caller should retry addQueueEntry() later. Negative codes
// (errors) and AQE_OK return false.
//
// aqeRetryImmediately(code) returns true only for
// AQE_DIR_CHANGE_PAUSE_INJECTED. This code means a direction-change pause
// was queued but the submitted command was not yet enqueued, so the caller
// should retry addQueueEntry() immediately (without waiting) to enqueue it.
// All other codes return false.
//
// aqeIsOk(code) returns true only for AQE_OK, i.e. the command was added
// successfully.
AqeResultCode addQueueEntry(const struct stepper_command_s* cmd,
bool start = true);
// ### check functions for command queue being empty, full or running.
bool isQueueEmpty() const;
bool isQueueFull() const;
bool isQueueRunning() const;
// ### functions to get the fill level of the queue
//
// To retrieve the forward planning time in the queue, ticksInQueue()
// can be used. It sums up all ticks of the not yet processed commands.
// For commands defining pauses, the summed up value is entry.ticks.
// For commands with steps, the summed up value is entry.steps*entry.ticks
uint32_t ticksInQueue() const;
// This function can be used to check, if the commands in the queue
// will last for <min_ticks> ticks. This is again without the
// currently processed command.
bool hasTicksInQueue(uint32_t min_ticks) const;
// This function allows to check the number of commands in the queue.
// This is including the currently processed command.
uint8_t queueEntries() const;
// Get the future position of the stepper after all commands in queue are
// completed
int32_t getPositionAfterCommandsCompleted() const;
// Get the future speed of the stepper after all commands in queue are
// completed. This is in µs. Returns 0 for stopped motor
//
// This value comes from the ramp generator and is not valid for raw command
// queue
// ==> Will be renamed in future release
uint32_t getPeriodInUsAfterCommandsCompleted() const;
uint32_t getPeriodInTicksAfterCommandsCompleted() const;
// Set the future position of the stepper after all commands in queue are
// completed. This has immediate effect to getCurrentPosition().
void setPositionAfterCommandsCompleted(int32_t new_pos);
// This function provides info, in which state the high level stepper control
// is operating. The return value is an `or` of RAMP_STATE_... and
// RAMP_DIRECTION_... flags. Definitions are above
inline uint8_t rampState() const { return _rg.rampState(); }
// returns true, if the ramp generation is active
inline bool isRampGeneratorActive() const {
return _rg.isRampGeneratorActive();
}
// These functions allow to detach and reAttach a step pin for other use.
// Pretty low level, use with care or not at all
void detachFromPin();
void reAttachToPin();
// ## ESP32 only: Free pulse counter
// These four functions are only available on esp32.
// The first can attach any of the eight pulse counters to this stepper.
// The second then will read the current pulse counter value
//
// The user is responsible to not use a pulse counter, which is occupied by a
// stepper and by this render the stepper or even blow up the uC.
//
// Pulse counter 6 and 7 are not used by the stepper library and are judged as
// available. If only five steppers are defined, then 5 gets available. If
// four steppers are defined, then 4 is usable,too.
//
// These functions are the way to read the pulses that have already left
// the step pin. getCurrentPosition() leads that pin while a move is
// running, because the driver pipelines steps. readPulseCounter() is
// the count of edges already emitted. The same hooks are used by the
// hardware tests.
//
// The pulse counter counts up towards high_value.
// If the high_value is reached, then the pulse counter is reset to 0.
// Similarly, if direction pin is configured and set to count down,
// then the pulse counter counts towards low_value. When the low value is hit,
// the pulse counter is reset to 0.
//
// If low_value and high_value are set to zero, then the pulse counter is just
// counting like any int16_t counter: 0...32767,-32768,-32767,...,0 and
// backwards accordingly
//
// Possible application:
// Assume the stepper, to which the pulse counter attached to, needs 3200
// steps/revolution. If now attachToPulseCounter is called with -3200 and 3200
// for the low and high values respectively, then the momentary angle of the
// stepper (at exact this moment) can be retrieved just by reading the pulse
// counter. If the value is negative, then just add 3200.
//
// In case external direction pin is used and the dir pin is available on one
// of the GPIOs, then the additional dir_pin_readback parameter informs
// about this pin.
//
// By default the pulse counter increments on the rising edge of the step
// pulse (low-to-high). Set invert_step_pulse to true to increment on the
// falling edge instead, for inverted step polarity.
//
// Update for idf5/idf6 version:
// The pcnt_unit value is not used, because the available units are managed
// by the system. The parameter is kept for compatibility.
//
#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR >= 5)
bool attachToPulseCounter(uint8_t unused_pcnt_unit = 0,
int16_t low_value = -16384,
int16_t high_value = 16384,
uint8_t dir_pin_readback = PIN_UNDEFINED,
bool invert_step_pulse = false);
int16_t readPulseCounter();
void clearPulseCounter();
inline bool pulseCounterAttached() { return _attached_pulse_unit != NULL; }
#endif
#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR == 4)
bool attachToPulseCounter(uint8_t pcnt_unit, int16_t low_value = -16384,
int16_t high_value = 16384,
uint8_t dir_pin_readback = PIN_UNDEFINED,
bool invert_step_pulse = false);
int16_t readPulseCounter();
void clearPulseCounter();
inline bool pulseCounterAttached() { return _attached_pulse_cnt_unit >= 0; }
#endif
#if defined(SUPPORT_SELECT_DRIVER_TYPE)
// Get the driver type (RMT, MCPWM_PCNT, I2S_DIRECT, I2S_MUX) used by this
// stepper. Only available on ESP32 when multiple driver types are supported.
FasDriver driverType() const;
const char* driverTypeString() const;
#endif
private:
void performOneStep(bool count_up, bool blocking = false);
void fill_queue();
void updateAutoDisable();
void blockingWaitForForceStopComplete();
bool needAutoDisable();
bool agreeWithAutoDisable();
bool usesAutoEnablePin(uint8_t pin);
void getCurrentSpeedInTicks(struct actual_ticks_s* speed,
bool realtime) const;
bool handleExternalDirectionPin(class StepperQueue* q, bool count_up);
class StepperQueue* _queue() const;
bool setEnablePinState(uint8_t pin, uint8_t active_state);
FastAccelStepperEngine* _engine;
RampGenerator _rg;
uint8_t _stepPin;
uint8_t _dirPin;
bool _dirHighCountsUp;
bool _autoEnable;
uint8_t _enablePinLowActive;
uint8_t _enablePinHighActive;
uint8_t _queue_num;
uint16_t _dir_change_delay_ticks;
uint32_t _on_delay_ticks;
uint16_t _off_delay_count;
uint16_t _auto_disable_delay_counter;