-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalexander.cpp
More file actions
146 lines (125 loc) · 2.99 KB
/
alexander.cpp
File metadata and controls
146 lines (125 loc) · 2.99 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
#include "alexander.h"
#include "constants.cpp"
int lastError = 0;
const float Kp = 1.4;
const float Kd = 1.1;
void basicLineFollower(int baseSpeed = 45)
{
int error;
if (readUltrasonicData() < 20)
{
controlSpeed(0, 0);
return;
}
if (
!readMiddleLeftIRData() &&
!readCenterIRData() &&
!readMiddleRightIRData())
{
error = lastError;
}
// Lurus
else if (readCenterIRData())
{
if (readCenterIRData() == 1 || readCenterIRData() == 3 || readCenterIRData() == 5)
error = 0;
else if (readCenterIRData() == 2)
error = -10;
else if (readCenterIRData() == 4)
error = 10;
}
// Kiri tengah
else if (readMiddleLeftIRData() && !readRightIRData())
{
error = -30;
}
// Kanan tengah
else if (!readLeftIRData() && readMiddleRightIRData())
{
error = 30;
}
// Calculate derivative of the error
int DError = error - lastError;
// Calculate additional speed needed
float additionalSpeed = Kp * error + Kd * DError;
if (error == 0)
controlSpeed(55, 55);
else
controlSpeed(baseSpeed + additionalSpeed, baseSpeed - additionalSpeed);
// Save current error as last error
lastError = error;
}
void find_line(int type, int pass_through = 1)
{
int left_found = 0;
int right_found = 0;
if (type == T_JUNCTION)
{
while (left_found == 0 || right_found == 0)
{
if (readLeftIRData() == 1)
{
left_found = 1;
}
if (readRightIRData() == 1)
{
right_found = 1;
}
basicLineFollower();
}
if (pass_through)
{
while (readLeftIRData() == 1 && readRightIRData() == 1)
{
basicLineFollower();
}
}
}
else if (type == LEFT_JUNCTION)
{
while (left_found == 0 || (left_found == 1 && !readMiddleLeftIRData()))
{
if (readLeftIRData() && readCenterIRData())
{
left_found = 1;
}
basicLineFollower();
}
if (pass_through)
{
while (readLeftIRData() == 1)
{
basicLineFollower();
}
}
}
else if (type == RIGHT_JUNCTION)
{
while (right_found == 0 || (right_found == 1 && !readMiddleRightIRData()))
{
if (readRightIRData() && readCenterIRData())
{
right_found = 1;
}
basicLineFollower();
}
if (pass_through)
{
while (readRightIRData() == 1)
{
basicLineFollower();
}
}
}
}
void grabTrolley()
{
// Operate servo
controlServo(120, 60);
delay(300);
// Mundur sedikit
controlSpeed(-50, -50);
delay(200);
controlSpeed(0, 0);
delay(500);
}