-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLine_Folloowing_Robot.ino
More file actions
387 lines (306 loc) · 9.33 KB
/
Line_Folloowing_Robot.ino
File metadata and controls
387 lines (306 loc) · 9.33 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
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
const bool REVERSE_STEERING = true;
const bool INVERT_LEFT_MOTOR = true;
const bool INVERT_RIGHT_MOTOR = true;
const int ENA = 10;
const int IN1 = 9;
const int IN2 = 8;
const int IN3 = 7;
const int IN4 = 6;
const int ENB = 5;
const int TRIG_PIN = 3;
const int ECHO_PIN = 4;
const int SENSOR_COUNT = 8;
const int sensorPins[SENSOR_COUNT] = {A0, A1, A2, A3, A4, A5, A6, A7};
int sensorMin[SENSOR_COUNT];
int sensorMax[SENSOR_COUNT];
const int HISTORY_SIZE = 10;
int pathHistory[HISTORY_SIZE];
int historyIndex = 0;
unsigned long lastHistoryWrite = 0;
float Kp = 0.08;
float Ki = 0.0001;
float Kd = 1.2;
float P, I, D;
float error = 0;
float lastError = 0;
float smoothedDerivative = 0;
const float integralLimit = 5000;
int currentBaseSpeed = 80;
const int targetBaseSpeed = 130;
const int maxSpeed = 220;
const int turnSpeed = 130;
const int minMotorSpeed = 110;
const int speedRampRate = 2;
unsigned long lastRampTime = 0;
const int stopDistance = 10;
unsigned long lastSonarCheck = 0;
int currentDistance = 999;
int recoveryAttempts = 0;
unsigned long lostLineTime = 0;
const unsigned long maxRecoveryTime = 3000;
enum RobotState {
CALIBRATING,
RUNNING,
LOST_LINE,
OBSTACLE_DETECTED,
STOPPED
};
RobotState currentState = CALIBRATING;
void setup() {
Serial.begin(9600);
pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); pinMode(ENB, OUTPUT);
pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT);
pinMode(13, OUTPUT); // LED
for (int i = 0; i < SENSOR_COUNT; i++) {
pinMode(sensorPins[i], INPUT);
sensorMin[i] = 1023;
sensorMax[i] = 0;
}
for(int i = 0; i < HISTORY_SIZE; i++) pathHistory[i] = 0;
Serial.println(F("=== LINE FOLLOWER ROBOT ==="));
Serial.println(F("Calibrating... Move sensors over line and background!"));
digitalWrite(13, HIGH);
unsigned long startTime = millis();
while (millis() - startTime < 5000) {
calibrateSensors();
if ((millis() - startTime) % 500 < 10) {
Serial.print(F("."));
}
}
digitalWrite(13, LOW);
Serial.println();
Serial.println(F("Calibration complete!"));
Serial.println(F("Sensor ranges (Min/Max):"));
for (int i = 0; i < SENSOR_COUNT; i++) {
Serial.print(F("S"));
Serial.print(i);
Serial.print(F(": "));
Serial.print(sensorMin[i]);
Serial.print(F("/"));
Serial.println(sensorMax[i]);
}
delay(1000);
Serial.println(F("Starting in 3 seconds..."));
delay(3000);
currentState = RUNNING;
Serial.println(F("GO!"));
}
void loop() {
// 1. Obstacle Check (non-blocking)
if (millis() - lastSonarCheck > 60) {
lastSonarCheck = millis();
currentDistance = getDistance();
}
if (currentDistance > 0 && currentDistance < stopDistance) {
if (currentState != OBSTACLE_DETECTED) {
Serial.print(F("OBSTACLE at "));
Serial.print(currentDistance);
Serial.println(F("cm"));
currentState = OBSTACLE_DETECTED;
}
stopMotors();
return;
} else if (currentState == OBSTACLE_DETECTED) {
currentState = RUNNING;
Serial.println(F("Path clear, resuming"));
}
// 2. Velocity Ramping (smooth acceleration)
if (millis() - lastRampTime > 50 && currentBaseSpeed < targetBaseSpeed) {
currentBaseSpeed += speedRampRate;
if (currentBaseSpeed > targetBaseSpeed) currentBaseSpeed = targetBaseSpeed;
lastRampTime = millis();
}
// 3. Read Sensors with improved filtering
int position = readLinePosition();
// 4. Calculate Error
error = 3500 - position;
// 5. Update Path History
if (millis() - lastHistoryWrite > 50) {
lastHistoryWrite = millis();
pathHistory[historyIndex] = (int)error;
historyIndex++;
if (historyIndex >= HISTORY_SIZE) historyIndex = 0;
}
// 6. Lost Line Detection and Recovery
if (abs(error) == 3500) {
if (currentState != LOST_LINE) {
lostLineTime = millis();
recoveryAttempts = 0;
currentState = LOST_LINE;
Serial.println(F("Line lost! Recovering..."));
}
// Timeout check
if (millis() - lostLineTime > maxRecoveryTime) {
Serial.println(F("Recovery timeout! Stopping."));
stopMotors();
currentState = STOPPED;
return;
}
recoverLostLine();
return;
} else if (currentState == LOST_LINE) {
currentState = RUNNING;
Serial.println(F("Line reacquired!"));
I = 0; // Reset integral on recovery
}
// 7. PID Calculation
P = error;
// Integral with windup prevention
I += error;
I = constrain(I, -integralLimit, integralLimit);
// Derivative with smoothing
float rawDerivative = error - lastError;
smoothedDerivative = (smoothedDerivative * 0.7) + (rawDerivative * 0.3);
D = smoothedDerivative;
float motorSpeedCorrection = (Kp * P) + (Ki * I) + (Kd * D);
lastError = error;
// 8. Motor Speed Calculation
int leftMotorSpeed, rightMotorSpeed;
if (REVERSE_STEERING) {
leftMotorSpeed = currentBaseSpeed + motorSpeedCorrection;
rightMotorSpeed = currentBaseSpeed - motorSpeedCorrection;
} else {
leftMotorSpeed = currentBaseSpeed - motorSpeedCorrection;
rightMotorSpeed = currentBaseSpeed + motorSpeedCorrection;
}
leftMotorSpeed = constrain(leftMotorSpeed, -maxSpeed, maxSpeed);
rightMotorSpeed = constrain(rightMotorSpeed, -maxSpeed, maxSpeed);
drive(leftMotorSpeed, rightMotorSpeed);
// 9. Debug output (every 200ms)
static unsigned long lastDebug = 0;
if (millis() - lastDebug > 200) {
lastDebug = millis();
Serial.print(F("Pos:"));
Serial.print(position);
Serial.print(F(" Err:"));
Serial.print((int)error);
Serial.print(F(" L:"));
Serial.print(leftMotorSpeed);
Serial.print(F(" R:"));
Serial.println(rightMotorSpeed);
}
}
//SENSOR READING
int readLinePosition() {
int mappedValues[SENSOR_COUNT];
int maxVal = 0;
int maxIndex = 0;
bool lineFound = false;
int activeSensors = 0;
for (int i = 0; i < SENSOR_COUNT; i++) {
int val = analogRead(sensorPins[i]);
mappedValues[i] = map(val, sensorMin[i], sensorMax[i], 0, 1000);
mappedValues[i] = constrain(mappedValues[i], 0, 1000);
// Noise filter with slightly higher threshold
if (mappedValues[i] < 60) mappedValues[i] = 0;
// Active sensor detection
if (mappedValues[i] > 600) activeSensors++;
// Track maximum
if (mappedValues[i] > maxVal) {
maxVal = mappedValues[i];
maxIndex = i;
}
// Line detection threshold
if (mappedValues[i] > 150) lineFound = true;
}
// INTERSECTION DETECTION
if (activeSensors > 5) {
return 3500;
}
// LINE NOT FOUND
if (!lineFound) {
// Return extreme value based on last known direction
if (REVERSE_STEERING) return (lastError < 0) ? 0 : 7000;
else return (lastError < 0) ? 7000 : 0;
}
// WEIGHTED AVERAGE CALCULATION
long weightedSum = 0;
long sum = 0;
int startIdx = max(0, maxIndex - 1);
int endIdx = min(SENSOR_COUNT - 1, maxIndex + 1);
for (int i = startIdx; i <= endIdx; i++) {
if (mappedValues[i] > 50) {
weightedSum += (long)mappedValues[i] * (i * 1000L);
sum += mappedValues[i];
}
}
if (sum == 0) return 3500;
return (int)(weightedSum / sum);
}
// --- SMART RECOVERY WITH EXPONENTIAL SEARCH ---
void recoverLostLine() {
long totalHistory = 0;
for(int i = 0; i < HISTORY_SIZE; i++) {
totalHistory += pathHistory[i];
}
float averageError = totalHistory / (float)HISTORY_SIZE;
bool turnRight = (averageError < 0);
recoveryAttempts++;
int searchSpeed = turnSpeed + (recoveryAttempts * 5);
searchSpeed = constrain(searchSpeed, turnSpeed, maxSpeed);
if (turnRight) {
drive(searchSpeed, -searchSpeed);
} else {
drive(-searchSpeed, searchSpeed);
}
}
// --- CALIBRATION ---
void calibrateSensors() {
for (int i = 0; i < SENSOR_COUNT; i++) {
int val = analogRead(sensorPins[i]);
if (val > sensorMax[i]) sensorMax[i] = val;
if (val < sensorMin[i]) sensorMin[i] = val;
}
}
// --- ULTRASONIC SENSOR ---
int getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 8000);
if (duration == 0) return 999;
int distance = duration * 0.034 / 2;
return distance;
}
// --- MOTOR CONTROL ---
int preventStall(int pwm) {
if (abs(pwm) < 40) return 0;
if (pwm > 0 && pwm < minMotorSpeed) return minMotorSpeed;
if (pwm < 0 && pwm > -minMotorSpeed) return -minMotorSpeed;
return pwm;
}
void drive(int leftSpeed, int rightSpeed) {
leftSpeed = preventStall(leftSpeed);
rightSpeed = preventStall(rightSpeed);
// Left Motor
bool leftForward = !INVERT_LEFT_MOTOR;
if (leftSpeed < 0) {
leftForward = !leftForward;
leftSpeed = -leftSpeed;
}
digitalWrite(IN1, leftForward ? HIGH : LOW);
digitalWrite(IN2, leftForward ? LOW : HIGH);
// Right Motor
bool rightForward = !INVERT_RIGHT_MOTOR;
if (rightSpeed < 0) {
rightForward = !rightForward;
rightSpeed = -rightSpeed;
}
digitalWrite(IN3, rightForward ? HIGH : LOW);
digitalWrite(IN4, rightForward ? LOW : HIGH);
// Set speeds
analogWrite(ENA, leftSpeed);
analogWrite(ENB, rightSpeed);
}
void stopMotors() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
analogWrite(ENA, 0);
analogWrite(ENB, 0);
I = 0;
}