-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlineMotions.cpp
71 lines (56 loc) · 1.5 KB
/
lineMotions.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
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "lineMotions.h"
#include "sensors.h"
#include "motor.h"
#include "Timers.h"
#include "defines.h"
static int oldError;
void startLineFollowing(int spd) {
oldError = 0; // reset the error
setMotion(spd, 0);
TMRArd_InitTimer(LINE_FOLLOW_TIMER, LINE_FOLLOW_UPDATE_PERIOD);
}
static int getMax(int val[]) {
int max = val[0];
if (max < val[1])
max = val[1];
if (max < val[2])
max = val[2];
return max;
}
char followLine(int spd) {
if (TMRArd_IsTimerExpired(LINE_FOLLOW_TIMER) != TMRArd_EXPIRED)
return LINE_FOLLOW_OK;
// reinit the timer
TMRArd_InitTimer(LINE_FOLLOW_TIMER, LINE_FOLLOW_UPDATE_PERIOD);
int val[3];
char retVal;
if (spd > 0)
readFrontSensors(val);
else
readBackSensors(val);
int min = removeMin(val);
int max = getMax(val);
int correction = 0;
int error = getLinePos(val);
// check min and max to determine
// where all sensors covered, or all sensors on white
if (min > LINE_SENSOR_MIN_THRES) { // all black
retVal = LINE_FOLLOW_ALL_LINE;
}
else if (max < LINE_SENSOR_MAX_THRES) { // no line found (values too close)
retVal = LINE_FOLLOW_NO_LINE;
}
else {
correction = (error * LINE_KP) >> 3; // Proportional component
correction += (error - oldError) * LINE_KD; // Derivative control
retVal = LINE_FOLLOW_OK;
}
adjustMotion(spd, -correction);
oldError = error;
return retVal;
}