-
Notifications
You must be signed in to change notification settings - Fork 0
/
ITSHServo.cpp
92 lines (72 loc) · 1.58 KB
/
ITSHServo.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
#include "ITSHServo.h"
#include "math.h"
ITSHServo::~ITSHServo() {
if(_moveStrategy) {
delete _moveStrategy;
}
}
void ITSHServo::setup() {
_servo.attach(_pin);
}
void ITSHServo::moveTo(int end, boolean easing) {
if(end < _min) {
end = _min;
}
if(end > _max) {
end = _max;
}
if(end == _currentPosition) {
return;
}
if(_moveStrategy) {
delete _moveStrategy;
}
if(easing) {
_moveStrategy = new ITSHServoMoveEasing(_currentPosition, end);
} else {
_moveStrategy = new ITSHServoMoveLinear(_currentPosition, end);
}
}
void ITSHServo::updatePosition(int position) {
_currentPosition = position;
_servo.write(_currentPosition);
}
boolean ITSHServo::loop() {
if(_currentPosition == -1) {
updatePosition(_home);
return true;
}
if(_moveStrategy && !_moveStrategy->isDone()) {
updatePosition(_moveStrategy->nextPosition());
return true;
}
return false;
}
boolean ITSHServoMove::isDone() {
return _target == _current;
}
int ITSHServoMoveLinear::nextPosition() {
if (_target > _start) {
_current++;
} else {
_current--;
}
return _current;
}
int ITSHServoMoveEasing::nextPosition() {
int relativeChange = _target - _start;
int totalTime = floor(abs(relativeChange) / 2);
_current = ceil(sineEaseInOut(_step, _start, relativeChange, totalTime));
if (abs(_target - _current) <= 1) {
_current = _target;
}
_step++;
return _current;
}
int ITSHServoMoveEasing::sineEaseInOut(int t, int b, int c, int d)
{
if (d == 0) {
return b + c;
}
return -c / 2 * (cos(M_PI * t / d) - 1) + b;
}