Arduino SA
Search…
Line Tracking Mode
In this mode, the car will follow a black solid line.

Code

1
//define L298n module IO Pin
2
int ENA = 5;
3
int IN1 = 3;
4
int IN2 = 4;
5
6
int ENB = 6;
7
int IN3 = 2;
8
int IN4 = 7;
9
10
#define ENASpeed 100
11
#define ENBSpeed 100
12
13
int Sensor1 = 0;
14
int Sensor2 = 0;
15
int Sensor3 = 0;
16
int Sensor4 = 0;
17
18
void setup() {
19
20
pinMode(ENA, OUTPUT);
21
pinMode(IN1, OUTPUT);
22
pinMode(IN2, OUTPUT);
23
24
pinMode(ENB, OUTPUT);
25
pinMode(IN3, OUTPUT);
26
pinMode(IN4, OUTPUT);
27
28
pinMode(Sensor1, INPUT);
29
pinMode(Sensor2, INPUT);
30
pinMode(Sensor3, INPUT);
31
pinMode(Sensor4, INPUT);
32
Serial.begin(9600);
33
}
34
35
void loop() {
36
digitalWrite(ENA, HIGH);
37
digitalWrite(ENB, HIGH);
38
39
Sensor1 = digitalRead(8);
40
Sensor2 = digitalRead(9);
41
Sensor3 = digitalRead(10);
42
Sensor4 = digitalRead(11);
43
44
if (Sensor4 == LOW && Sensor3 == LOW && Sensor2 == HIGH && Sensor1 == HIGH)
45
{
46
digitalWrite(IN1, LOW);
47
digitalWrite(IN2, HIGH);
48
49
digitalWrite(IN3, LOW);
50
digitalWrite(IN4, HIGH);
51
Serial.println("left");
52
}
53
else if (Sensor4 == HIGH && Sensor3 == HIGH && Sensor2 == LOW && Sensor1 == LOW)
54
{
55
56
digitalWrite(IN1, HIGH);
57
digitalWrite(IN2, LOW);
58
59
digitalWrite(IN3, HIGH);
60
digitalWrite(IN4, LOW);
61
Serial.println("right");
62
}
63
64
else if (Sensor4 == LOW && Sensor3 == HIGH && Sensor2 == HIGH && Sensor1 == LOW)
65
{
66
67
//FORWARD
68
digitalWrite(IN1, HIGH);
69
digitalWrite(IN2, LOW);
70
digitalWrite(IN3, LOW);
71
digitalWrite(IN4, HIGH);
72
Serial.println("run");
73
}
74
75
else if (Sensor4 == LOW && Sensor3 == LOW && Sensor2 == LOW && Sensor1 == LOW)
76
{
77
78
digitalWrite(IN1, LOW);
79
digitalWrite(IN2, HIGH);
80
digitalWrite(IN3, HIGH);
81
digitalWrite(IN4, LOW);
82
Serial.println("run");
83
}
84
85
}
Copied!

Code Explanation

When Sensor1 and Sensor2 infrared sensors detect the black line, and Sensor3 and Sensor4 do not detect the black line, then MCU controls the L298N module to make the car turn right. When Sensor3 and Sensor4 infrared sensors detect the black line, and Sensor1 and Sensor2 do not detect the black line, then MCU controls the L298N module to make the car turn left. When the black line is detected by Sensor3 and Sensor2 infrared sensors and no black line is detected by Sensor1 and Sensor4, the MCU controls the L298N module to make the car move forward.
When the black line is not detected by Sensor1, Sensor2, Sensor3 and Sensor4 infrared sensors, the MCU controls the L298N module to make the car move back.
Last modified 3mo ago
Copy link