-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathServoEasing.hpp
2774 lines (2488 loc) · 111 KB
/
ServoEasing.hpp
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
/*
* ServoEasing.hpp
*
* Enables smooth movement from one servo position to another.
* Linear as well as other ease movements (e.g. cubic) for all servos attached to the Arduino Servo library are provided.
* Interface is in degree but internally only microseconds (if using Servo library) or units (if using PCA9685 expander) are used,
* since the resolution is better and we avoid the map function on every Servo.write().
* The blocking functions wait for 20 ms since this is the default refresh time of the used Servo library.
*
* The AVR Servo library supports only one timer, which means not more than 12 servos are supported using this library.
*
* Copyright (C) 2019-2022 Armin Joachimsmeyer
*
* This file is part of ServoEasing https://github.com/ArminJo/ServoEasing.
*
* ServoEasing 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*/
/*
* This library can be configured at compile time by the following options / macros:
* For more details see: https://github.com/ArminJo/ServoEasing#compile-options--macros-for-this-library
*
* - USE_PCA9685_SERVO_EXPANDER Enables the use of the PCA9685 I2C expander chip/board.
* - USE_SERVO_LIB Use of PCA9685 normally disables use of regular servo library. You can force additional using of regular servo library by defining USE_SERVO_LIB.
* - USE_LEIGHTWEIGHT_SERVO_LIB Makes the servo pulse generating immune to other libraries blocking interrupts for a longer time like SoftwareSerial, Adafruit_NeoPixel and DmxSimple.
* - PROVIDE_ONLY_LINEAR_MOVEMENT Disables all but LINEAR movement. Saves up to 1540 bytes program memory.
* - DISABLE_COMPLEX_FUNCTIONS Disables the SINE, CIRCULAR, BACK, ELASTIC, BOUNCE and PRECISION easings.
* - MAX_EASING_SERVOS Saves 4 byte RAM per servo.
* - DISABLE_MICROS_AS_DEGREE_PARAMETER Disables passing also microsecond values as (target angle) parameter. Saves 128 bytes program memory.
* - PRINT_FOR_SERIAL_PLOTTER Generate serial output for Arduino Plotter (Ctrl-Shift-L).
*/
#ifndef _SERVO_EASING_HPP
#define _SERVO_EASING_HPP
#include <Arduino.h>
#include "ServoEasing.h"
#if defined(USE_LEIGHTWEIGHT_SERVO_LIB) && (defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__))
#include "LightweightServo.hpp" // include sources of LightweightServo library
#endif
/*
* Enable this to see information on each call.
* Since there should be no library which uses Serial, it should only be enabled for development purposes.
*/
#if defined(DEBUG)
#define LOCAL_DEBUG
#else
//#define LOCAL_DEBUG // This enables debug output only for this file
#endif
#if defined(TRACE)
#define LOCAL_TRACE
// Propagate debug level
#define LOCAL_DEBUG
#else
//#define LOCAL_TRACE // This enables trace output only for this file
#endif
// Enable this if you want to measure timing by toggling pin12 on an arduino
//#define MEASURE_SERVO_EASING_INTERRUPT_TIMING
#if defined(MEASURE_SERVO_EASING_INTERRUPT_TIMING)
#include "digitalWriteFast.h"
#define TIMING_OUTPUT_PIN 12
#endif
#if defined(ESP8266) || defined(ESP32)
//# if defined(ESP32)
//#include "esp_task_wdt.h" // for esp_task_wdt_reset();
//# endif
#include "Ticker.h" // for ServoEasingInterrupt functions
Ticker Timer20ms;
// BluePill in 2 flavors
#elif defined(STM32F1xx) // for "Generic STM32F1 series / STM32:stm32" from STM32 Boards from STM32 cores of Arduino Board manager
// https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json
#include <HardwareTimer.h> // 4 timers and 3. timer is used for tone(), 2. for Servo
/*
* Use timer 4 as IRMP timer.
* Timer 4 blocks PB6, PB7, PB8, PB9, so if you require one of them as Servo output, you must choose another timer.
*/
HardwareTimer Timer20ms(TIM4);
#elif defined(__STM32F1__) // or ARDUINO_ARCH_STM32F1 for "Generic STM32F103C series / stm32duino:STM32F1" from STM32F1 Boards (STM32duino.com) of Arduino Board manager
// http://dan.drown.org/stm32duino/package_STM32duino_index.json
#include <HardwareTimer.h>
# if defined(STM32_HIGH_DENSITY)
HardwareTimer Timer20ms(7); // 8 timers and 8. timer is used for tone()
# else
/*
* Use timer 3 for ServoEasingInterrupt functions.
* Timer 3 blocks PA6, PA7, PB0, PB1, so if you required one of them as Servo output, you must choose another timer.
*/
HardwareTimer Timer20ms(3); // 4 timers and 4. timer is used for tone()
# endif
#elif defined(__SAM3X8E__) // Arduino DUE
/*
* Timer 0 to 5 are used by Servo library (by defining handlers)
*
* Timer 6 is TC2 channel 0
* Timer 7 is TC2 channel 1
* Timer 8 is TC2 channel 2
*
* We use timer 8 here
*/
#define TC_FOR_20_MS_TIMER TC2
#define CHANNEL_FOR_20_MS_TIMER 2
#define ID_TC_FOR_20_MS_TIMER ID_TC8 // Timer 8 is TC2 channel 2
#define IRQn_FOR_20_MS_TIMER TC8_IRQn
#define HANDLER_FOR_20_MS_TIMER TC8_Handler
#elif defined(ARDUINO_ARCH_MBED) // Arduino Nano 33 BLE + Sparkfun Apollo3
mbed::Ticker Timer20ms;
/*************************************************************************************************************************************
* RP2040 based boards for pico core
* https://github.com/earlephilhower/arduino-pico
* https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json
* Can use any pin for PWM, no timer restrictions
*************************************************************************************************************************************/
#elif defined(ARDUINO_ARCH_RP2040) // Raspberry Pi Pico, Adafruit Feather RP2040, etc.
#include "pico/time.h"
repeating_timer_t Timer20ms;
void handleServoTimerInterrupt();
// The timer callback has a parameter and a return value
bool handleServoTimerInterruptHelper(repeating_timer_t*) {
handleServoTimerInterrupt();
return true;
}
#elif defined(TEENSYDUINO)
// common for all Teensy
IntervalTimer Timer20ms;
#endif
volatile bool ServoEasing::sInterruptsAreActive = false; // true if interrupts are still active, i.e. at least one Servo is moving with interrupts.
/**
* list to hold all ServoEasing Objects in order to move them together
* Cannot use "static servo_t servos[MAX_SERVOS];" from Servo library since it is static :-(
*/
uint_fast8_t ServoEasing::sServoArrayMaxIndex = 0; // maximum index of an attached servo in ServoEasing::ServoEasingArray[]
ServoEasing *ServoEasing::ServoEasingArray[MAX_EASING_SERVOS];
/**
* Used exclusively for *ForAllServos() functions. Is updated by write() or startEaseToD() function, to keep it synchronized.
* Can contain degree values or microseconds but not units.
* Use float since we want to support higher precision for degrees.
*/
float ServoEasing::ServoEasingNextPositionArray[MAX_EASING_SERVOS];
const char easeTypeLinear[] PROGMEM = "linear";
#if !defined(PROVIDE_ONLY_LINEAR_MOVEMENT)
const char easeTypeQuadratic[] PROGMEM = "quadratic";
const char easeTypeCubic[] PROGMEM = "cubic";
const char easeTypeQuartic[] PROGMEM = "quartic";
const char easeTypePrecision[] PROGMEM = "precision";
const char easeTypeUser[] PROGMEM = "user";
const char easeTypeNotDefined[] PROGMEM = "";
const char easeTypeDummy[] PROGMEM = "dummy";
# if !defined(DISABLE_COMPLEX_FUNCTIONS)
const char easeTypeSine[] PROGMEM = "sine";
const char easeTypeCircular[] PROGMEM = "circular";
const char easeTypeBack[] PROGMEM = "back";
const char easeTypeElastic[] PROGMEM = "elastic";
const char easeTypeBounce[] PROGMEM = "bounce";
# endif
#endif // !defined(PROVIDE_ONLY_LINEAR_MOVEMENT)
const char *const easeTypeStrings[] PROGMEM = { easeTypeLinear
#if !defined(PROVIDE_ONLY_LINEAR_MOVEMENT)
, easeTypeQuadratic, easeTypeCubic, easeTypeQuartic, easeTypeNotDefined, easeTypeNotDefined, easeTypeUser, easeTypeDummy,
# if !defined(DISABLE_COMPLEX_FUNCTIONS)
easeTypeSine, easeTypeCircular, easeTypeBack, easeTypeElastic, easeTypeBounce, easeTypePrecision
# endif
#endif
};
#if defined(USE_PCA9685_SERVO_EXPANDER)
//#define USE_SOFT_I2C_MASTER // Saves 2110 bytes program memory and 200 bytes RAM compared with Arduino Wire
# if defined(USE_SOFT_I2C_MASTER)
#include "SoftI2CMasterConfig.h"
#include "SoftI2CMaster.h"
# endif // defined(USE_SOFT_I2C_MASTER)
# if !defined _BV
# define _BV(bit) (1 << (bit))
# endif
// Constructor with I2C address required
#if defined(USE_SOFT_I2C_MASTER)
ServoEasing::ServoEasing(uint8_t aPCA9685I2CAddress) // @suppress("Class members should be properly initialized")
#else
ServoEasing::ServoEasing(uint8_t aPCA9685I2CAddress, TwoWire *aI2CClass) // @suppress("Class members should be properly initialized")
#endif
{
mPCA9685I2CAddress = aPCA9685I2CAddress;
#if !defined(USE_SOFT_I2C_MASTER)
mI2CClass = aI2CClass;
#endif
// On an ESP8266 it was NOT initialized to 0 :-(.
mTrimMicrosecondsOrUnits = 0;
mSpeed = START_EASE_TO_SPEED;
mServoMoves = false;
mOperateServoReverse = false;
#if defined(USE_SERVO_LIB)
mServoIsConnectedToExpander = true;
#endif
#if !defined(PROVIDE_ONLY_LINEAR_MOVEMENT)
mEasingType = EASE_LINEAR;
# if defined(ENABLE_EASE_USER)
mUserEaseInFunction = NULL;
# endif
#endif
TargetPositionReachedHandler = NULL;
#if !defined(DISABLE_MIN_AND_MAX_CONSTRAINTS)
mMinMicrosecondsOrUnits = 0;
mMaxMicrosecondsOrUnits = 2 * DEFAULT_MICROSECONDS_FOR_180_DEGREE; // any big value is sufficient
#endif
#if defined(MEASURE_SERVO_EASING_INTERRUPT_TIMING)
pinMode(TIMING_OUTPUT_PIN, OUTPUT);
#endif
}
void ServoEasing::I2CInit() {
// Initialize I2C
#if defined(USE_SOFT_I2C_MASTER)
i2c_init(); // Initialize everything and check for bus lockup
#else
mI2CClass->begin();
mI2CClass->setClock(I2C_CLOCK_FREQUENCY); // 1000000 does not work for me, maybe because of parasitic breadboard capacities
# if defined (ARDUINO_ARCH_AVR) // Other platforms do not have this new function
mI2CClass->setWireTimeout(); // Sets default timeout of 25 ms.
# endif
#endif
}
/**
* Initialize I2C and software reset all PCA9685 expanders
*/
void ServoEasing::PCA9685Reset() {
// Send software reset to expander(s)
#if defined(USE_SOFT_I2C_MASTER)
i2c_start(PCA9685_GENERAL_CALL_ADDRESS << 1);
i2c_write(PCA9685_SOFTWARE_RESET);
i2c_stop();
#else
mI2CClass->beginTransmission(PCA9685_GENERAL_CALL_ADDRESS);
mI2CClass->write(PCA9685_SOFTWARE_RESET);
mI2CClass->endTransmission();
#endif
}
/**
* Set expander to 20 ms period for 4096-part cycle and wait 2 milliseconds
* This results in a resolution of 4.88 us per step.
*/
void ServoEasing::PCA9685Init() {
// Set expander to 20 ms period
I2CWriteByte(PCA9685_MODE1_REGISTER, _BV(PCA9685_MODE_1_SLEEP)); // go to sleep
I2CWriteByte(PCA9685_PRESCALE_REGISTER, PCA9685_PRESCALER_FOR_20_MS); // set the prescaler
I2CWriteByte(PCA9685_MODE1_REGISTER, _BV(PCA9685_MODE_1_AUTOINCREMENT)); // reset sleep and enable auto increment
delay(2); // > 500 us according to datasheet
}
void ServoEasing::I2CWriteByte(uint8_t aAddress, uint8_t aData) {
#if defined(USE_SOFT_I2C_MASTER)
i2c_start(mPCA9685I2CAddress << 1);
i2c_write(aAddress);
i2c_write(aData);
i2c_stop();
#else
mI2CClass->beginTransmission(mPCA9685I2CAddress);
mI2CClass->write(aAddress);
mI2CClass->write(aData);
# if defined(LOCAL_DEBUG)
uint8_t tWireReturnCode = mI2CClass->endTransmission();
if (tWireReturnCode != 0) {
// I have seen this at my ESP32 module :-( - but it is no buffer overflow.
Serial.print((char) (tWireReturnCode + '0')); // Error enum i2c_err_t: I2C_ERROR_ACK = 2, I2C_ERROR_TIMEOUT = 3
}
# else
mI2CClass->endTransmission();
# endif
#endif
}
/**
* @param aPWMValueAsUnits - The point in the 4096-part cycle, where the output goes OFF (LOW). On is fixed at 0.
* Useful values are from 111 (111.411 = 544 us) to 491 (491.52 = 2400 us)
* This results in an resolution of approximately 0.5 degree.
* 4096 means output is signal fully off
*/
void ServoEasing::setPWM(uint16_t aPWMOffValueAsUnits) {
#if defined(USE_SOFT_I2C_MASTER)
i2c_start(mPCA9685I2CAddress << 1);
i2c_write((PCA9685_FIRST_PWM_REGISTER + 2) + 4 * mServoPin);
i2c_write(aPWMOffValueAsUnits);
i2c_write(aPWMOffValueAsUnits >> 8);
i2c_stop();
#else
mI2CClass->beginTransmission(mPCA9685I2CAddress);
// +2 since we we do set the OFF value and not the ON value, which is fixed at 0
mI2CClass->write((PCA9685_FIRST_PWM_REGISTER + 2) + 4 * mServoPin); // 4 * mServoPin is the register offset
mI2CClass->write(aPWMOffValueAsUnits);
mI2CClass->write(aPWMOffValueAsUnits >> 8);
# if defined(LOCAL_DEBUG) && not defined(ESP32)
// The ESP32 I2C interferes with the Ticker / Timer library used.
// Even with 100 kHz clock we have some dropouts / NAK's because of sending address again instead of first data.
uint8_t tWireReturnCode = mI2CClass->endTransmission();
if (tWireReturnCode != 0) {
// If you end up here, maybe the second module is not attached?
Serial.print((char) (tWireReturnCode + '0')); // Error enum i2c_err_t: I2C_ERROR_ACK = 2, I2C_ERROR_TIMEOUT = 3
}
# else
mI2CClass->endTransmission();
# endif
#endif
}
/**
* Here you can specify an on/start value for the pulse in order not to start all pulses at the same time.
* Is used by _writeMicrosecondsOrUnits() with onValue as mServoPin * 235
* Requires 550 us to send data => 8.8 ms for 16 Servos, 17.6 ms for 32 servos. => more than 2 expander boards
* cannot be connected to one I2C bus, if all servos must be able to move simultaneously.
*/
void ServoEasing::setPWM(uint16_t aPWMOnStartValueAsUnits, uint16_t aPWMPulseDurationAsUnits) {
#if defined(USE_SOFT_I2C_MASTER)
i2c_start(mPCA9685I2CAddress << 1);
i2c_write((PCA9685_FIRST_PWM_REGISTER) + 4 * mServoPin);
i2c_write(aPWMOnStartValueAsUnits);
i2c_write(aPWMOnStartValueAsUnits >> 8);
i2c_write(aPWMOnStartValueAsUnits + aPWMPulseDurationAsUnits);
i2c_write((aPWMOnStartValueAsUnits + aPWMPulseDurationAsUnits) >> 8);
i2c_stop();
#else
mI2CClass->beginTransmission(mPCA9685I2CAddress);
mI2CClass->write((PCA9685_FIRST_PWM_REGISTER) + 4 * mServoPin);
mI2CClass->write(aPWMOnStartValueAsUnits);
mI2CClass->write(aPWMOnStartValueAsUnits >> 8);
mI2CClass->write(aPWMOnStartValueAsUnits + aPWMPulseDurationAsUnits);
mI2CClass->write((aPWMOnStartValueAsUnits + aPWMPulseDurationAsUnits) >> 8);
# if defined(LOCAL_DEBUG) && not defined(ESP32)
// The ESP32 I2C interferes with the Ticker / Timer library used.
// Even with 100 kHz clock we have some dropouts / NAK's because of sending address again instead of first data.
uint8_t tWireReturnCode = mI2CClass->endTransmission(); // blocking call
if (tWireReturnCode != 0) {
// If you end up here, maybe the second module is not attached?
Serial.print((char) (tWireReturnCode + '0')); // Error enum i2c_err_t: I2C_ERROR_ACK = 2, I2C_ERROR_TIMEOUT = 3
}
# else
mI2CClass->endTransmission();
# endif
#endif
}
int ServoEasing::MicrosecondsToPCA9685Units(int aMicroseconds) {
/*
* 4096 units per 20 milliseconds => aMicroseconds / 4.8828
*/
#if defined(USE_SERVO_LIB)
if (!mServoIsConnectedToExpander) {
return aMicroseconds; // we must return microseconds here
}
#endif
return ((4096L * aMicroseconds) / REFRESH_INTERVAL_MICROS);
}
int ServoEasing::PCA9685UnitsToMicroseconds(int aPCA9685Units) {
/*
* 4096 units per 20 milliseconds => aPCA9685Units * 4.8828
* (aPCA9685Units * 625) / 128 use int32_t to avoid overflow
*/
return ((int32_t) aPCA9685Units * (REFRESH_INTERVAL_MICROS / 32)) / (4096 / 32);
}
#endif // defined(USE_PCA9685_SERVO_EXPANDER)
// Constructor without I2C address
ServoEasing::ServoEasing() // @suppress("Class members should be properly initialized")
#if (!defined(USE_PCA9685_SERVO_EXPANDER) || defined(USE_SERVO_LIB)) && !defined(USE_LEIGHTWEIGHT_SERVO_LIB)
:
Servo()
#endif
{
// On an ESP8266 it was NOT initialized to 0 :-(.
mTrimMicrosecondsOrUnits = 0;
mSpeed = START_EASE_TO_SPEED;
mServoMoves = false;
#if !defined(DISABLE_PAUSE_RESUME)
mServoIsPaused = false;
#endif
mOperateServoReverse = false;
#if defined(USE_PCA9685_SERVO_EXPANDER) && defined(USE_SERVO_LIB)
mServoIsConnectedToExpander = false;
#endif
#if !defined(PROVIDE_ONLY_LINEAR_MOVEMENT)
mEasingType = EASE_LINEAR;
# if defined(ENABLE_EASE_USER)
mUserEaseInFunction = NULL;
# endif
#endif
TargetPositionReachedHandler = NULL;
#if !defined(DISABLE_MIN_AND_MAX_CONSTRAINTS)
mMinMicrosecondsOrUnits = 0;
mMaxMicrosecondsOrUnits = 2 * DEFAULT_MICROSECONDS_FOR_180_DEGREE; // any big value is sufficient
#endif
#if defined(MEASURE_SERVO_EASING_INTERRUPT_TIMING)
pinMode(TIMING_OUTPUT_PIN, OUTPUT);
#endif
}
/**
* Specify the microseconds values for 0 and 180 degree for the servo.
* The values can be determined by the EndPositionsTest example.
* @param aPin Pin number or port number of PCA9685 [0-15]
*
* If USE_LEIGHTWEIGHT_SERVO_LIB is enabled:
* Return 0/false if not pin 9 or 10 else return aPin
* Pin number != 9 results in using pin 10.
* If USE_PCA9685_SERVO_EXPANDER is enabled:
* Return true only if channel number is between 0 and 15 since PCA9685 has only 16 channels, else returns false
* Else return servoIndex / internal channel number
*/
uint8_t ServoEasing::attach(int aPin) {
return attach(aPin, DEFAULT_MICROSECONDS_FOR_0_DEGREE, DEFAULT_MICROSECONDS_FOR_180_DEGREE);
}
// Here no units accepted, only microseconds!
uint8_t ServoEasing::attach(int aPin, int aMicrosecondsForServo0Degree, int aMicrosecondsForServo180Degree) {
return attach(aPin, aMicrosecondsForServo0Degree, aMicrosecondsForServo180Degree, 0, 180);
}
/**
* Combination of attach with initial write().
*/
uint8_t ServoEasing::attach(int aPin, int aInitialDegreeOrMicrosecond) {
return attach(aPin, aInitialDegreeOrMicrosecond, DEFAULT_MICROSECONDS_FOR_0_DEGREE, DEFAULT_MICROSECONDS_FOR_180_DEGREE);
}
/**
* Combination of attach with initial setTrim() and write().
*/
uint8_t ServoEasing::attachWithTrim(int aPin, int aTrimDegreeOrMicrosecond, int aInitialDegreeOrMicrosecond) {
return attachWithTrim(aPin, aTrimDegreeOrMicrosecond, aInitialDegreeOrMicrosecond, DEFAULT_MICROSECONDS_FOR_0_DEGREE,
DEFAULT_MICROSECONDS_FOR_180_DEGREE);
}
/**
* Specify the start value written to the servo and the microseconds values for 0 and 180 degree for the servo.
* The values can be determined by the EndPositionsTest example.
* By modifying the Micoseconds* parameter values you can also provide an initial trim.
* Initial trim is the behavior for mTrimMicrosecondsOrUnits == 0.
*/
uint8_t ServoEasing::attach(int aPin, int aInitialDegreeOrMicrosecond, int aMicrosecondsForServo0Degree,
int aMicrosecondsForServo180Degree) {
return attach(aPin, aInitialDegreeOrMicrosecond, aMicrosecondsForServo0Degree, aMicrosecondsForServo180Degree, 0, 180);
}
uint8_t ServoEasing::attachWithTrim(int aPin, int aTrimDegreeOrMicrosecond, int aInitialDegreeOrMicrosecond,
int aMicrosecondsForServo0Degree, int aMicrosecondsForServo180Degree) {
return attachWithTrim(aPin, aTrimDegreeOrMicrosecond, aInitialDegreeOrMicrosecond, aMicrosecondsForServo0Degree,
aMicrosecondsForServo180Degree, 0, 180);
}
/**
* The microseconds values at aServoLowDegree and aServoHighDegree are used to compute the microseconds values at 0 and 180 degrees
* By modifying the Micoseconds* and *Degree parameter values you can also provide an initial trim and reverse.
* Initial trim is the behavior for mTrimMicrosecondsOrUnits == 0.
* This can be used e.g. to run the servo from virtual -90 to +90 degree (See TwoServos example).
*/
uint8_t ServoEasing::attach(int aPin, int aInitialDegreeOrMicrosecond, int aMicrosecondsForServoLowDegree,
int aMicrosecondsForServoHighDegree, int aServoLowDegree, int aServoHighDegree) {
uint8_t tReturnValue = attach(aPin, aMicrosecondsForServoLowDegree, aMicrosecondsForServoHighDegree, aServoLowDegree,
aServoHighDegree);
write(aInitialDegreeOrMicrosecond);
return tReturnValue;
}
uint8_t ServoEasing::attachWithTrim(int aPin, int aTrimDegreeOrMicrosecond, int aInitialDegreeOrMicrosecond,
int aMicrosecondsForServoLowDegree, int aMicrosecondsForServoHighDegree, int aServoLowDegree, int aServoHighDegree) {
uint8_t tReturnValue = attach(aPin, aMicrosecondsForServoLowDegree, aMicrosecondsForServoHighDegree, aServoLowDegree,
aServoHighDegree);
setTrim(aTrimDegreeOrMicrosecond, false);
write(aInitialDegreeOrMicrosecond);
return tReturnValue;
}
/**
* Attaches servo to pin and sets the servo timing parameters.
* @param aPin Pin number or port number of PCA9685 [0-15]
* @param aMicrosecondsForServoLowDegree, aMicrosecondsForServoHighDegree no units accepted, only microseconds!
* @param aServoLowDegree can be negative. For this case an appropriate trim value is added, since this is the only way to handle negative values.
* @param aServoHighDegree The degree value for the corresponding aMicrosecondsForServoHighDegree parameter.
* @return If USE_LEIGHTWEIGHT_SERVO_LIB is enabled:
* Return 0/false if not pin 9 or 10 else return aPin
* Pin number != 9 results in using pin 10.
* Else return servoIndex / internal channel number
*/
uint8_t ServoEasing::attach(int aPin, int aMicrosecondsForServoLowDegree, int aMicrosecondsForServoHighDegree, int aServoLowDegree,
int aServoHighDegree) {
/*
* Get the 0 and 180 degree values.
*/
int tMicrosecondsForServo0Degree = map(0, aServoLowDegree, aServoHighDegree, aMicrosecondsForServoLowDegree,
aMicrosecondsForServoHighDegree);
int tMicrosecondsForServo180Degree = map(180, aServoLowDegree, aServoHighDegree, aMicrosecondsForServoLowDegree,
aMicrosecondsForServoHighDegree);
mServoPin = aPin;
#if defined(USE_PCA9685_SERVO_EXPANDER)
# if defined(USE_SERVO_LIB)
if (mServoIsConnectedToExpander) {
// set units
mServo0DegreeMicrosecondsOrUnits = MicrosecondsToPCA9685Units(tMicrosecondsForServo0Degree);
mServo180DegreeMicrosecondsOrUnits = MicrosecondsToPCA9685Units(tMicrosecondsForServo180Degree);
} else {
// set microseconds
mServo0DegreeMicrosecondsOrUnits = tMicrosecondsForServo0Degree;
mServo180DegreeMicrosecondsOrUnits = tMicrosecondsForServo180Degree;
}
# else
// set units
mServo0DegreeMicrosecondsOrUnits = MicrosecondsToPCA9685Units(tMicrosecondsForServo0Degree);
mServo180DegreeMicrosecondsOrUnits = MicrosecondsToPCA9685Units(tMicrosecondsForServo180Degree);
# endif
#else
// set microseconds
mServo0DegreeMicrosecondsOrUnits = tMicrosecondsForServo0Degree;
mServo180DegreeMicrosecondsOrUnits = tMicrosecondsForServo180Degree;
#endif
/*
* Now put this servo instance into list of servos
*/
uint8_t tReturnValue = INVALID_SERVO; // flag indicating an invalid servo index
for (uint_fast8_t tServoIndex = 0; tServoIndex < MAX_EASING_SERVOS; ++tServoIndex) {
if (ServoEasingArray[tServoIndex] == NULL) {
ServoEasingArray[tServoIndex] = this;
tReturnValue = tServoIndex;
if (tServoIndex > sServoArrayMaxIndex) {
sServoArrayMaxIndex = tServoIndex;
}
break;
}
}
mServoIndex = tReturnValue;
#if defined(LOCAL_TRACE)
Serial.print("Index=");
Serial.print(tReturnValue);
Serial.print(" pin=");
Serial.print(mServoPin);
Serial.print(" low=");
Serial.print(aServoLowDegree);
Serial.print('|');
Serial.print(aMicrosecondsForServoLowDegree);
Serial.print(" high=");
Serial.print(aServoHighDegree);
Serial.print('|');
Serial.print(aMicrosecondsForServoHighDegree);
Serial.print(' ');
printStatic(&Serial);
#endif
#if defined(USE_PCA9685_SERVO_EXPANDER)
mCurrentMicrosecondsOrUnits = DEFAULT_PCA9685_UNITS_FOR_90_DEGREE; // The start value if we forget the initial write()
# if defined(USE_SERVO_LIB)
if (mServoIsConnectedToExpander) {
if (tReturnValue == 0) {
I2CInit(); // init only once
PCA9685Reset(); // reset only once
}
PCA9685Init(); // initialize at every attach is simpler but initializing once for every board would be sufficient.
return tReturnValue;
}
# else
if (tReturnValue == 0) {
I2CInit(); // init only once
PCA9685Reset(); // reset only once
}
PCA9685Init(); // initialize at every attach is simpler but initializing once for every board would be sufficient.
return tReturnValue;
# endif
#endif // defined(USE_PCA9685_SERVO_EXPANDER)
#if !defined(USE_PCA9685_SERVO_EXPANDER) || defined(USE_SERVO_LIB)
/*
* Here servo is NOT connected to expander
*/
mCurrentMicrosecondsOrUnits = DEFAULT_PULSE_WIDTH; // The start value if we forget the initial write()
// This error value has priority over the regular return value from Servo::attach()
if (tReturnValue == INVALID_SERVO) {
return tReturnValue;
}
# if defined(USE_LEIGHTWEIGHT_SERVO_LIB)
if(aPin != 9 && aPin != 10) {
return false;
}
return aPin;
# else
/*
* Use standard arduino servo library
* Call attach() of the underlying Servo library
*/
# if defined(ARDUINO_ARCH_APOLLO3)
Servo::attach(aPin, tMicrosecondsForServo0Degree, tMicrosecondsForServo180Degree);
return aPin; // Sparkfun apollo3 Servo library has no return value for attach :-(
# else
return Servo::attach(aPin, tMicrosecondsForServo0Degree, tMicrosecondsForServo180Degree);
# endif // defined(ARDUINO_ARCH_APOLLO3)
# endif // defined(USE_LEIGHTWEIGHT_SERVO_LIB)
#endif // defined(USE_SERVO_LIB)
}
/**
* Mark a detached servo in the array by setting the object pointer to NULL
* The next attach() then uses this NULL pointer position and thus gets the index of the former detached one.
*/
void ServoEasing::detach() {
if (mServoIndex != INVALID_SERVO) {
ServoEasingArray[mServoIndex] = NULL;
// If servo with highest index in array was detached, we want to find new sServoArrayMaxIndex
while (ServoEasingArray[sServoArrayMaxIndex] == NULL && sServoArrayMaxIndex > 0) {
sServoArrayMaxIndex--;
}
#if defined(USE_PCA9685_SERVO_EXPANDER)
# if defined(USE_SERVO_LIB)
if (mServoIsConnectedToExpander) {
setPWM(0); // set signal fully off
} else {
# if defined(USE_LEIGHTWEIGHT_SERVO_LIB)
deinitLightweightServoPin9_10(mServoPin == 9, mServoPin == 10); // disable output and change to input
# else
Servo::detach();
# endif
}
# else
setPWM(0); // set signal fully off
# endif // defined(USE_SERVO_LIB)
#else
# if defined(USE_LEIGHTWEIGHT_SERVO_LIB)
deinitLightweightServoPin9_10(mServoPin == 9, mServoPin == 10); // disable output and change to input
# else
Servo::detach();
# endif
#endif // defined(USE_PCA9685_SERVO_EXPANDER)
}
mServoMoves = false; // safety net to enable right update handling if accidentally called
mServoIndex = INVALID_SERVO;
}
/**
* @note Reverse means, that values for 180 and 0 degrees are swapped by: aValue = mServo180DegreeMicrosecondsOrUnits - (aValue - mServo0DegreeMicrosecondsOrUnits)
* Be careful, if you specify different end values, it may not behave, as you expect.
* For this case better use the attach function with 5 parameter.
* This flag is only used at _writeMicrosecondsOrUnits()
*/
void ServoEasing::setReverseOperation(bool aOperateServoReverse) {
mOperateServoReverse = aOperateServoReverse;
}
uint_fast16_t ServoEasing::getSpeed() {
return mSpeed;
}
void ServoEasing::setSpeed(uint_fast16_t aDegreesPerSecond) {
mSpeed = aDegreesPerSecond;
}
/**
* @param aTrimDegreeOrMicrosecond This trim value is always added to the degree/units/microseconds value requested
* @param aDoWrite If true, apply value directly to servo by calling _writeMicrosecondsOrUnits() using mCurrentMicrosecondsOrUnits
* This shows the effect of the trim as a servo movement
* If false, no internal value e.g. ServoEasingNextPositionArray or mCurrentMicrosecondsOrUnits is updated!
*/
void ServoEasing::setTrim(int aTrimDegreeOrMicrosecond, bool aDoWrite) {
if (aTrimDegreeOrMicrosecond >= 0) {
_setTrimMicrosecondsOrUnits(
DegreeOrMicrosecondToMicrosecondsOrUnits(aTrimDegreeOrMicrosecond) - mServo0DegreeMicrosecondsOrUnits, aDoWrite);
} else {
_setTrimMicrosecondsOrUnits(
-(DegreeOrMicrosecondToMicrosecondsOrUnits(-aTrimDegreeOrMicrosecond) - mServo0DegreeMicrosecondsOrUnits),
aDoWrite);
}
}
/**
* @param aTrimMicrosecondsOrUnits This trim value is always added to the degree/units/microseconds value requested
* @param aDoWrite If true, apply value directly to servo by calling _writeMicrosecondsOrUnits() using mCurrentMicrosecondsOrUnits
* This shows the effect of the trim as a servo movement
* If false, no internal value e.g. ServoEasingNextPositionArray or mCurrentMicrosecondsOrUnits is updated!
* @note mTrimMicrosecondsOrUnits is exclusively added by _writeMicrosecondsOrUnits()
*/
void ServoEasing::_setTrimMicrosecondsOrUnits(int aTrimMicrosecondsOrUnits, bool aDoWrite) {
mTrimMicrosecondsOrUnits = aTrimMicrosecondsOrUnits;
if (aDoWrite) {
_writeMicrosecondsOrUnits(mCurrentMicrosecondsOrUnits);
}
}
#if !defined(DISABLE_MIN_AND_MAX_CONSTRAINTS)
void ServoEasing::setMaxConstraint(int aMaxDegreeOrMicrosecond) {
mMaxMicrosecondsOrUnits = DegreeOrMicrosecondToMicrosecondsOrUnits(aMaxDegreeOrMicrosecond);
}
void ServoEasing::setMinConstraint(int aMinDegreeOrMicrosecond) {
mMinMicrosecondsOrUnits = DegreeOrMicrosecondToMicrosecondsOrUnits(aMinDegreeOrMicrosecond);
}
void ServoEasing::setMinMaxConstraint(int aMinDegreeOrMicrosecond, int aMaxDegreeOrMicrosecond) {
mMinMicrosecondsOrUnits = DegreeOrMicrosecondToMicrosecondsOrUnits(aMinDegreeOrMicrosecond);
mMaxMicrosecondsOrUnits = DegreeOrMicrosecondToMicrosecondsOrUnits(aMaxDegreeOrMicrosecond);
}
#endif
#if !defined(PROVIDE_ONLY_LINEAR_MOVEMENT)
void ServoEasing::setEasingType(uint_fast8_t aEasingType) {
mEasingType = aEasingType;
}
uint_fast8_t ServoEasing::getEasingType() {
return (mEasingType);
}
# if defined(ENABLE_EASE_USER)
void ServoEasing::registerUserEaseInFunction(float (*aUserEaseInFunction)(float aFactorOfTimeCompletion, void *aUserDataPointer),
void *aUserDataPointer) {
mUserEaseInFunction = aUserEaseInFunction;
UserDataPointer = aUserDataPointer;
}
void ServoEasing::setUserDataPointer(void *aUserDataPointer) {
UserDataPointer = aUserDataPointer;
}
# endif
#endif // !defined(PROVIDE_ONLY_LINEAR_MOVEMENT)
/**
* @param aTargetDegreeOrMicrosecond treat values less than 400 as angles in degrees, others are handled as microseconds
*/
void ServoEasing::write(int aTargetDegreeOrMicrosecond) {
#if defined(LOCAL_TRACE)
Serial.print(F("write "));
Serial.print(aTargetDegreeOrMicrosecond);
Serial.print(' ');
#endif
/*
* Check for valid initialization of servo.
*/
if (mServoIndex == INVALID_SERVO) {
#if defined(LOCAL_TRACE)
Serial.print(F("Error: detached servo"));
#endif
return;
}
ServoEasingNextPositionArray[mServoIndex] = aTargetDegreeOrMicrosecond;
_writeMicrosecondsOrUnits(DegreeOrMicrosecondToMicrosecondsOrUnits(aTargetDegreeOrMicrosecond));
}
void ServoEasing::write(float aTargetDegreeOrMicrosecond) {
#if defined(LOCAL_TRACE)
Serial.print(F("write "));
Serial.print(aTargetDegreeOrMicrosecond);
Serial.print(' ');
#endif
/*
* Check for valid initialization of servo.
*/
if (mServoIndex == INVALID_SERVO) {
#if defined(LOCAL_TRACE)
Serial.print(F("Error: detached servo"));
#endif
return;
}
ServoEasingNextPositionArray[mServoIndex] = aTargetDegreeOrMicrosecond;
_writeMicrosecondsOrUnits(DegreeOrMicrosecondToMicrosecondsOrUnits(aTargetDegreeOrMicrosecond));
}
/**
* Internal function
* Before sending the value to the underlying Servo library, trim and reverse is applied
*/
void ServoEasing::_writeMicrosecondsOrUnits(int aTargetDegreeOrMicrosecond) {
/*
* Check for valid initialization of servo.
*/
if (mServoIndex == INVALID_SERVO) {
#if defined(LOCAL_TRACE)
Serial.print(F("Error: detached servo"));
#endif
return;
}
#if !defined(DISABLE_MIN_AND_MAX_CONSTRAINTS)
if (aTargetDegreeOrMicrosecond > mMaxMicrosecondsOrUnits) {
aTargetDegreeOrMicrosecond = mMaxMicrosecondsOrUnits;
} else if (aTargetDegreeOrMicrosecond < mMinMicrosecondsOrUnits) {
aTargetDegreeOrMicrosecond = mMinMicrosecondsOrUnits;
}
#endif
mCurrentMicrosecondsOrUnits = aTargetDegreeOrMicrosecond;
#if defined(LOCAL_TRACE)
Serial.print(mServoIndex);
Serial.print('/');
Serial.print(mServoPin);
Serial.print(F(" us/u="));
Serial.print(aTargetDegreeOrMicrosecond);
if (mTrimMicrosecondsOrUnits != 0) {
Serial.print(" t=");
Serial.print(aTargetDegreeOrMicrosecond + mTrimMicrosecondsOrUnits);
}
#endif // TRACE
// Apply trim - this is the only place mTrimMicrosecondsOrUnits is evaluated
aTargetDegreeOrMicrosecond += mTrimMicrosecondsOrUnits;
// Apply reverse, values for 0 to 180 are swapped if reverse - this is the only place mOperateServoReverse is evaluated
// (except in the DegreeToMicrosecondsOrUnitsWithTrimAndReverse() function for external testing purposes)
if (mOperateServoReverse) {
aTargetDegreeOrMicrosecond = mServo180DegreeMicrosecondsOrUnits
- (aTargetDegreeOrMicrosecond - mServo0DegreeMicrosecondsOrUnits);
#if defined(LOCAL_TRACE)
Serial.print(F(" r="));
Serial.print(aTargetDegreeOrMicrosecond);
#endif
}
#if defined(PRINT_FOR_SERIAL_PLOTTER) && !defined(LOCAL_TRACE)
Serial.print(' '); // leading separator to separate multiple servo values
Serial.print(aTargetDegreeOrMicrosecond);
#endif
#if defined(USE_PCA9685_SERVO_EXPANDER)
# if defined(LOCAL_TRACE)
// For each pin show PWM on value used below
Serial.print(F(" s="));
Serial.print(mServoPin * (4096 - (DEFAULT_PCA9685_UNITS_FOR_180_DEGREE + 100)) / 15); // mServoPin * 233
# endif
# if defined(USE_SERVO_LIB)
if (mServoIsConnectedToExpander) {
setPWM(mServoPin * ((4096 - (DEFAULT_PCA9685_UNITS_FOR_180_DEGREE + 100)) / 15), aTargetDegreeOrMicrosecond); // mServoPin * 233
} else {
# if defined(USE_LEIGHTWEIGHT_SERVO_LIB)
writeMicrosecondsLightweightServo(aTargetDegreeOrMicrosecond, (mServoPin == 9));
# else
Servo::writeMicroseconds(aTargetDegreeOrMicrosecond); // requires 7 us
# endif
}
# else
/*
* Distribute the servo start time over the 20 ms period.
* Unexpectedly this even saves 20 bytes Flash for an ATmega328P
*/
setPWM(mServoPin * ((4096 - (DEFAULT_PCA9685_UNITS_FOR_180_DEGREE + 100)) / 15), aTargetDegreeOrMicrosecond); // mServoPin * 233
# endif
#else
# if defined(USE_LEIGHTWEIGHT_SERVO_LIB)
writeMicrosecondsLightweightServo(aTargetDegreeOrMicrosecond, (mServoPin == 9));
# else
Servo::writeMicroseconds(aTargetDegreeOrMicrosecond); // requires 7 us
# endif
#endif
#if defined(LOCAL_TRACE) && !defined(PRINT_FOR_SERIAL_PLOTTER)
Serial.println(); // no newline here, if serial plotter output is requested
#endif
}
/**
* Only used in startEaseTo to compute target degree
* For PCA9685, we have stored units in mServo0DegreeMicrosecondsOrUnits and mServo180DegreeMicrosecondsOrUnits
* @param aMicroseconds Always assume microseconds, thus for PCA9685 we must convert 0 and 180 degree values back to microseconds
*/
int ServoEasing::MicrosecondsToDegree(int aMicroseconds) {
#if defined(USE_PCA9685_SERVO_EXPANDER)
# if defined(USE_SERVO_LIB)
if (!mServoIsConnectedToExpander) {
return MicrosecondsOrUnitsToDegree(aMicroseconds); // not connected to PCA9685 here
}
# endif
int32_t tResult = aMicroseconds - PCA9685UnitsToMicroseconds(mServo0DegreeMicrosecondsOrUnits);
tResult = (tResult * 180) + 928;
return (tResult / PCA9685UnitsToMicroseconds((mServo180DegreeMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits)));
#else
return MicrosecondsOrUnitsToDegree(aMicroseconds);
#endif
}
/**
* Used to convert e.g. mCurrentMicrosecondsOrUnits back to degree
* @param aMicrosecondsOrUnits For servos connected to a PCA9685 assume units, else assume microseconds
* Do not use map function, because it does no rounding
*/
int ServoEasing::MicrosecondsOrUnitsToDegree(int aMicrosecondsOrUnits) {
/**
* Formula for microseconds:
* (aMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits) * (180 / 1856) // 1856 = 180 - 0 degree micros
* Formula for PCA9685 units
* (aMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits) * (180 / 380) // 380 = 180 - 0 degree units
* Formula for both without rounding
* map(aMicrosecondsOrUnits, mServo0DegreeMicrosecondsOrUnits, mServo180DegreeMicrosecondsOrUnits, 0, 180)
*/
/*
* compute map with rounding
*/
// remove zero degree offset
int32_t tResult = aMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits;
#if defined(USE_PCA9685_SERVO_EXPANDER)
# if defined(USE_SERVO_LIB)
if (mServoIsConnectedToExpander) {
// here we have PCA9685 units
tResult = (tResult * 180) + 190;
} else {
// here we deal with microseconds
tResult = (tResult * 180) + 928;
}
# else
// here we have PCA9685 units
tResult = (tResult * 180) + 190;
# endif
#else
// here we deal with microseconds
tResult = (tResult * 180) + 928; // 928 is the value for 1/2 degree before scaling; (1856 = 180 - 0 degree micros) / 2
#endif
// scale by 180 degree range (180 - 0 degree micros)
return (tResult / (mServo180DegreeMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits));
}
int ServoEasing::MicrosecondsOrUnitsToMicroseconds(int aMicrosecondsOrUnits) {
#if defined(USE_PCA9685_SERVO_EXPANDER)
return PCA9685UnitsToMicroseconds(aMicrosecondsOrUnits);
#else
return aMicrosecondsOrUnits; // we have microseconds here
#endif
}
/**
* We have around 10 us per degree
* Used to convert (external) provided degree values to internal microseconds
* For degree parameter, return map(aDegreeOrMicrosecond, 0, 180, mServo0DegreeMicrosecondsOrUnits, mServo180DegreeMicrosecondsOrUnits);
*/
int ServoEasing::DegreeOrMicrosecondToMicrosecondsOrUnits(int aDegreeOrMicrosecond) {
#if defined(DISABLE_MICROS_AS_DEGREE_PARAMETER)
return ((int32_t) (aDegreeOrMicrosecond * (int32_t) (mServo180DegreeMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits))
/ 180) + mServo0DegreeMicrosecondsOrUnits;
#else // defined(DISABLE_MICROS_AS_DEGREE_PARAMETER)
if (aDegreeOrMicrosecond < THRESHOLD_VALUE_FOR_INTERPRETING_VALUE_AS_MICROSECONDS) {
/*
* Here aDegreeOrMicrosecond contains degree
*/
// return map(aDegreeOrMicrosecond, 0, 180, mServo0DegreeMicrosecondsOrUnits, mServo180DegreeMicrosecondsOrUnits);
// This saves 20 bytes program space and is faster :-)
return ((int32_t) (aDegreeOrMicrosecond * (int32_t) (mServo180DegreeMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits))
/ 180L) + mServo0DegreeMicrosecondsOrUnits;
} else {
/*
* Here aDegreeOrMicrosecond contains microseconds
*/
# if defined(USE_PCA9685_SERVO_EXPANDER)
return MicrosecondsToPCA9685Units(aDegreeOrMicrosecond); // return units here
# else
return aDegreeOrMicrosecond; // return microseconds here
# endif
}
#endif // defined(DISABLE_MICROS_AS_DEGREE_PARAMETER)
}
int ServoEasing::DegreeOrMicrosecondToMicrosecondsOrUnits(float aDegreeOrMicrosecond) {
// For microseconds and PCA9685 units:
#if defined(DISABLE_MICROS_AS_DEGREE_PARAMETER)
return ((int32_t) (aDegreeOrMicrosecond * ((float) (mServo180DegreeMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits))))
/ 180 + mServo0DegreeMicrosecondsOrUnits; // return microseconds here
#else
if (aDegreeOrMicrosecond < THRESHOLD_VALUE_FOR_INTERPRETING_VALUE_AS_MICROSECONDS) {
/*
* Here aDegreeOrMicrosecond contains degree
*/
return ((int32_t) (aDegreeOrMicrosecond * ((float) (mServo180DegreeMicrosecondsOrUnits - mServo0DegreeMicrosecondsOrUnits))))
/ 180 + mServo0DegreeMicrosecondsOrUnits; // return microseconds here