💡 Sample Arduino Code for Line Following
This sample sketch helps your robot follow a black line using two IR sensors and an L298N motor driver.
// Pin configuration
int leftSensor = A0;
int rightSensor = A1;
int motorLeft1 = 9;
int motorLeft2 = 8;
int motorRight1 = 7;
int motorRight2 = 6;
void setup() {
pinMode(leftSensor, INPUT);
pinMode(rightSensor, INPUT);
pinMode(motorLeft1, OUTPUT);
pinMode(motorLeft2, OUTPUT);
pinMode(motorRight1, OUTPUT);
pinMode(motorRight2, OUTPUT);
}
void loop() {
int left = digitalRead(leftSensor);
int right = digitalRead(rightSensor);
if (left == 0 && right == 0) {
// Move forward
forward();
} else if (left == 0 && right == 1) {
// Turn left
turnLeft();
} else if (left == 1 && right == 0) {
// Turn right
turnRight();
} else {
// Stop
stopMotors();
}
}
void forward() {
digitalWrite(motorLeft1, HIGH);
digitalWrite(motorLeft2, LOW);
digitalWrite(motorRight1, HIGH);
digitalWrite(motorRight2, LOW);
}
void turnLeft() {
digitalWrite(motorLeft1, LOW);
digitalWrite(motorLeft2, HIGH);
digitalWrite(motorRight1, HIGH);
digitalWrite(motorRight2, LOW);
}
void turnRight() {
digitalWrite(motorLeft1, HIGH);
digitalWrite(motorLeft2, LOW);
digitalWrite(motorRight1, LOW);
digitalWrite(motorRight2, HIGH);
}
void stopMotors() {
digitalWrite(motorLeft1, LOW);
digitalWrite(motorLeft2, LOW);
digitalWrite(motorRight1, LOW);
digitalWrite(motorRight2, LOW);
}
🔌 Uploading the Code
- Connect Arduino to your computer using a USB cable.
- Open the Arduino IDE and paste the code above.
- Select the correct board and port under the Tools menu.
- Click the Upload button (arrow icon).
- Wait for "Done Uploading" message at the bottom.