Introduction: Why Build a Line-Following Car?

Building a line-following car with Arduino and sensors is one of the most rewarding beginner robotics projects. It teaches you the fundamentals of embedded programming, sensor feedback, motor control, and system integration in a tangible, hands-on way. More than just a fun toy, a line-following robot introduces concepts like state machines, threshold detection, and even basic proportional-integral-derivative (PID) control for smooth navigation. By the end of this expanded guide, you'll not only have a working car but also a deep understanding of how each component contributes to autonomous movement.

This project is ideal for high school or undergraduate engineering students, hobbyists, and makers who have basic experience with Arduino and electronics. The final vehicle can follow any dark line on a light surface (or vice versa), making it perfect for competition tracks, warehouse routing simulations, or just racing your friends.

Materials Needed

The following list covers all essential components. Some items have alternatives – choose based on availability or budget.

  • Microcontroller: Arduino Uno R3 (most common) or a compatible board like Arduino Nano, ESP32, or NodeMCU. Uno is easiest for beginners due to abundant tutorials.
  • Infrared (IR) Line Sensors: At least 2 sensors. Popular modules: TCRT5000, KY-033, or the 5-channel line sensor array. Two sensors are sufficient for a basic car; more sensors allow smoother tracking.
  • Motor Driver Module: L298N, L293D, or TB6612FNG. L298N is cheap and handles two DC motors up to 2A, but wastes power in linear mode. L293D is H-bridge but lower current. TB6612FNG is more efficient and compact.
  • DC Motors with Wheels: Two geared DC motors (e.g., 6V or 12V, around 100–300 RPM). Encoder motors are optional but useful for speed control.
  • Chassis or Frame: A pre-built acrylic or plastic car chassis (many kits include motors and wheels). Alternatively, 3D print your own or use a piece of rigid plastic/cardboard.
  • Breadboard and Jumper Wires: For prototyping connections. Use M/M, M/F, and F/F jumper wires as needed.
  • Power Supply: Battery pack – 4x AA (NiMH recommended) for Arduino and 6V motors, or separate Li-ion packs for logic and motors to reduce noise.
  • Optional: Switch (on/off), voltage regulator (if using higher voltage batteries), castor wheel or ball bearing caster for balance.

Understanding the Components

IR Line Sensors – How They Work

An IR line sensor module typically contains an infrared LED (emitter) and a photodiode or phototransistor (receiver). The emitter shines IR light downward; the intensity of reflected light depends on the surface color. Dark surfaces absorb IR, so the receiver sees little reflected IR (output goes HIGH or LOW depending on module logic). Light surfaces reflect strongly, so the receiver sees high intensity (output opposite). Most sensor modules have an onboard comparator (like LM393) that outputs a digital signal – usually HIGH for line, LOW for background or vice versa, adjustable via a potentiometer. Some modules also provide analog output, allowing you to measure reflectance intensity, which enables threshold calibration.

Motor Driver Board – L298N

The L298N is a dual H-bridge IC that can control two DC motors independently, including direction and speed (via PWM). Key pins: ENA (enable A, PWM for speed), IN1/IN2 (direction for motor A), ENB and IN3/IN4 for motor B. Without enabling PWM pins, motors run at full speed. A 5V regulator on the board can power the Arduino from the motor battery (jumper must be connected). However, it's often safer to use separate supplies to avoid brownouts.

Arduino Digital and PWM Pins

The Arduino Uno has 14 digital I/O pins (0–13). Pins 3,5,6,9,10,11 support PWM for speed control. We'll use pin 2 and 3 for left/right sensor digital inputs, and pins 9,10,5,6 for L298N control. Keep serial communication pins (0,1) free. Power the sensors and motor driver from the Arduino's 5V if current is under 500mA; otherwise use an external 5V regulator.

Assembling the Chassis

Start by mounting the motors onto the chassis. Most kits come with brackets or screw holes. Secure the motors so the wheels spin freely without rubbing the chassis. Attach the ball caster or swivel wheel to the front (or rear) for stability – a three-point contact (two driven wheels + caster) works well. Position the line sensor array under the front of the chassis, approximately 5–15mm above the ground. The exact height and angle affect sensitivity; you may need to experiment. If using individual sensors, space them about the width of the line apart (e.g., 2–4 cm). Mount the Arduino (with a shield or standoffs) in the center and the motor driver near the motors. Use a breadboard for sensor connections to keep wiring neat. Finally, attach the battery pack, ideally low on the chassis to lower the center of gravity.

Wiring the Electronics

Follow this wiring table for a standard two-sensor L298N setup. Confirm your specific modules' pin labels – some use "OUT" for digital output, others "D0".

ComponentPin / TerminalArduino Pin
Left sensorVCC5V
GNDGND
OUTDigital pin 2
Right sensorVCC5V
GNDGND
OUTDigital pin 3
L298N Motor Driver12V/+(motor supply)Battery pack positive
GNDBattery pack negative AND Arduino GND (common ground!)
5V (output)Arduino 5V (if using internal regulator) or leave unconnected if using USB power
ENAPWM pin 9
IN1Digital pin 10
IN2Digital pin 5
IN3Digital pin 6
IN4Digital pin 11
ENBPWM pin 3
Motor AOut1, Out2Left motor terminals
Motor BOut3, Out4Right motor terminals

Important: Always connect a common ground between Arduino, motor driver, and battery. Without it, signals may float and the motors won't work. Separate power for motors (6–12V) and logic (5V from Arduino/USB) is recommended. If using a single battery pack, the L298N's onboard regulator can power the Arduino, but ensure the battery voltage does not exceed 12V.

Programming the Arduino

Basic Logic – Two Sensors

The simplest algorithm uses two sensors to distinguish four states:

  • Both on line (e.g., both sensors HIGH if active-high for dark line): Drive straight.
  • Left sensor on line, right off: Turn left.
  • Right sensor on line, left off: Turn right.
  • Both off line: Stop or search (rotate to find line).

Below is a complete Arduino sketch with speed control. Note: sensor logic might be inverted depending on module. Adjust the ON_LINE constant and digitalRead() logic accordingly.

// Line-following car with Arduino
// Pins
const int leftSensorPin = 2;
const int rightSensorPin = 3;
const int ENA = 9; // Left motor PWM
const int IN1 = 10;
const int IN2 = 5;
const int IN3 = 6;
const int IN4 = 11;
const int ENB = 3; // Right motor PWM

// Speed (0-255)
int baseSpeed = 150;
int turnSpeed = 100;

void setup() {
  pinMode(leftSensorPin, INPUT);
  pinMode(rightSensorPin, INPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  for (int p : {IN1, IN2, IN3, IN4}) pinMode(p, OUTPUT);
  // Stop motors initially
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, LOW);
    digitalWrite(IN3, LOW);
    digitalWrite(IN4, LOW);
  delay(1000);
}

void loop() {
  int left = digitalRead(leftSensorPin);
  int right = digitalRead(rightSensorPin);
  // Assuming dark line = HIGH; adjust for your sensor
  const bool ON_LINE = HIGH;

  if (left == ON_LINE && right == ON_LINE) {
    moveForward(baseSpeed);
  } else if (left == ON_LINE && right != ON_LINE) {
    turnLeft(turnSpeed);
  } else if (right == ON_LINE && left != ON_LINE) {
    turnRight(turnSpeed);
  } else {
    stopMotors();
    // Optional: search pattern
    delay(100);
  }
}

void moveForward(int spd) {
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(ENA, spd);
  analogWrite(ENB, spd);
}

void turnLeft(int spd) {
  // Left motor reverse, right motor forward
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(ENA, spd);
  analogWrite(ENB, spd);
}

void turnRight(int spd) {
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  analogWrite(ENA, spd);
  analogWrite(ENB, spd);
}

void stopMotors() {
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(ENA, 0);
  analogWrite(ENB, 0);
}

Moving Beyond Simple Logic – PID Control

For smoother, faster line following, consider implementing a PD or PID controller using the sensor readings. Instead of two digital sensors, use an analog sensor array (e.g., 8-channel) to get a continuous "error" value. The error is the deviation from the line center. Then apply:

  • P term: steering proportional to error
  • D term: dampens oscillations by opposing rapid changes
  • I term (optional): eliminates steady-state error, but careful with integral windup

With PID, you can turn the car smoothly around corners without abrupt stops. For a simple two-sensor system, you can still implement a pseudo-P controller by using varying turn speeds based on which sensor is triggered (e.g., if left sensor triggers just barely, turn gently; if it's fully in the line, turn hard).

Testing and Calibration

  1. Test the sensors: Upload a simple sketch that prints sensor values to Serial Monitor (9600 baud). Move the car over a line and note the readings for line vs. background. Adjust the potentiometer on the sensor module so the digital output toggles reliably.
  2. Check motor directions: Run the code and verify forward, left turn, right turn. Swap motor wires on the L298N if directions are reversed.
  3. Baseline speed: Start with base speed ~100 (PWM 0-255). Increase gradually. If the car loses the line at corners, reduce speed or increase turnSpeed.
  4. Fine-tune the line: A thick black tape (1.5–2 cm wide) on a white surface is easiest. Matte tape reduces glare.
  5. Sensor height: Lower sensors detect smaller deviations but may scrape. Ideal height is 5–15mm. Use standoffs or spacers.

Troubleshooting Common Issues

SymptomPossible CauseSolution
Car doesn't move at allNo power, loose wires, or wrong pin connectionsCheck battery voltage, common ground, and motor driver enable pins (ENA/ENB must be HIGH).
Car moves forward but ignores the lineSensor logic inverted; sensors too high; line too faintSwap ON_LINE constant, lower sensors, increase tape contrast.
Car spins in circles or jerky motionOne sensor faulty; motor wiring crossPrint sensor readings; swap motor wires to test.
Car oscillates or wobbly on straightSpeed too high; sensor spacing too wideReduce speed; move sensors closer together.
Arduino resets when motors startPower supply dip due to motor current drawUse separate batteries for motors and logic; add large capacitors (100–470µF) across motor supply.

Advanced Modifications

Once the basic car works, you can upgrade it significantly:

  • Add more sensors: A 5- or 8-sensor array gives positional awareness, enabling PID control and wall following.
  • Use stepper motors: For precise speed control without PWM noise, but requires a stepper driver (A4988).
  • Obstacle detection: Add an ultrasonic sensor (HC-SR04) to stop before obstacles. Combine line following with obstacle avoidance logic.
  • Wireless control: Use an HC-05 bluetooth module to switch modes (manual remote vs. line follow).
  • Speed feedback: Add encoder wheels and use interrupts to measure actual speed, enabling closed-loop control.
  • Computer vision: For high-end projects, replace IR sensors with a camera module (OpenMV, Pixy2) and run color-based line detection.

Further Learning Resources

Conclusion

You've learned how to select components, assemble a chassis, wire the electronics, and program basic line-following behavior. More importantly, you've seen how sensor feedback drives decision-making in robotics. The simple state machine we used scales up to complex autonomous systems. Whether you're competing in a line-following contest or just exploring mechatronics, this project gives you a solid foundation. Experiment with different algorithms, add features, and most importantly – have fun building. The next time you see a autonomous warehouse robot, you'll know exactly what's under the hood.