-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotDriver.cpp
132 lines (90 loc) · 2.26 KB
/
RotDriver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include "RotDriver.h"
RotDriver::RotDriver() {
}
RotDriver::RotDriver(int _id){
id=_id;
forwardPin=24+4*id;
backwardPin=25+4*id;
pinMode(forwardPin,OUTPUT);
pinMode(backwardPin,OUTPUT);
speedPin=3+2*id; // Analog out
sensorPin=2*id+1; // Analog in
sensorMin=0;
sensorMax=1023;
highPower=255;
maxSpeed=127;
lowPowerPos=EEPROM.read(7*id+4);
lowPowerNeg=EEPROM.read(7*id+5);
zeroAngle=EEPROM.read(7*id+6);
}
bool RotDriver::calibrate(){
int length = 30;
int delayTime = 1000;
int lastValue = 0;
// Read zeroAngle (Player must face forward before calibration!)
zeroAngle=map(analogRead(sensorPin),sensorMin,sensorMax,0,255);
// Find lowPowerPos
lastValue = analogRead(sensorPin);
digitalWrite(forwardPin,1);
digitalWrite(backwardPin,0);
for(int i=30;i<255;i++){
if(abs(analogRead(sensorPin)-lastValue)>length) {
lowPowerPos=i;
break;
}
lastValue = analogRead(sensorPin);
analogWrite(speedPin,i);
delay(delayTime);
analogWrite(speedPin,0);
delay(100);
}
analogWrite(speedPin,0);
delay(500);
// Find lowPowerNeg
lastValue = analogRead(sensorPin);
digitalWrite(forwardPin,0);
digitalWrite(backwardPin,1);
for(int i=30;i<255;i++){
if(abs(analogRead(sensorPin)-lastValue)>length) {
lowPowerNeg=i;
break;
}
lastValue = analogRead(sensorPin);
analogWrite(speedPin,i);
delay(delayTime);
analogWrite(speedPin,0);
delay(100);
}
analogWrite(speedPin,0);
delay(500);
return true;
}
// Activate motor with chosen duty cycle
void RotDriver::setSpeed(int vel){
// Set speed
if(vel == 0) {
digitalWrite(forwardPin,0);
digitalWrite(backwardPin,0);
analogWrite(speedPin,0);
} else {
int lowPower = 0;
// Choose direction
if(vel > 0){
digitalWrite(forwardPin,1);
digitalWrite(backwardPin,0);
lowPower = lowPowerPos;
}else if(vel < 0){
digitalWrite(forwardPin,0);
digitalWrite(backwardPin,1);
lowPower = lowPowerNeg;
}
int finalPower=map(abs(vel),0,maxSpeed,lowPower,highPower);
analogWrite(speedPin,finalPower);
}
}
int RotDriver::readConstrained() {
return map(constrain(analogRead(sensorPin), sensorMin, sensorMax), sensorMin, sensorMax, 0, 255);
}
bool RotDriver::reset() {
return true;
}