IntermediateRobotics about 180 min

Line Follower Robot

A two-sensor robot that follows a black line on a white surface - the classic first robotics build.

Steps

  1. Assemble the chassis

    Fit the two BO motors and wheels to the 2WD chassis and add the caster/support wheel.

  2. Mount the sensors

    Fix the two IR sensor modules at the front, about 5-8 mm above the ground and slightly wider than the line.

  3. Wire the motor driver

    Connect the motors to the L298N outputs. Link ENA/ENB, IN1-IN4 to Nano pins 5, 6, 7, 8, 9, 10 as in the code.

  4. Wire the sensors

    Connect the left sensor OUT to D2 and the right sensor OUT to D3. Give them 5V and GND.

  5. Power it

    Feed the L298N 12V input from your battery pack and the 5V pin to the Nano 5V (or power the Nano separately).

  6. Upload and tune

    Upload the sketch. Turn the sensor potentiometers until the on-board LED lights on white and goes off on black (or the reverse - then flip the logic in the code).

Code

// Line follower: line (black) runs BETWEEN the two sensors
const int ENA = 5, IN1 = 7, IN2 = 8;     // left motor
const int ENB = 6, IN3 = 9, IN4 = 10;    // right motor
const int SENSOR_L = 2, SENSOR_R = 3;
const int SPEED = 150;

void drive(int l, int r) {               // -255 .. 255
  digitalWrite(IN1, l > 0); digitalWrite(IN2, l < 0); analogWrite(ENA, abs(l));
  digitalWrite(IN3, r > 0); digitalWrite(IN4, r < 0); analogWrite(ENB, abs(r));
}

void setup() {
  pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
  pinMode(SENSOR_L, INPUT); pinMode(SENSOR_R, INPUT);
}

void loop() {
  bool onLineL = digitalRead(SENSOR_L) == HIGH;   // HIGH = black surface (flip if yours is reversed)
  bool onLineR = digitalRead(SENSOR_R) == HIGH;

  if (!onLineL && !onLineR)      drive(SPEED, SPEED);      // line between sensors: go straight
  else if (onLineL && !onLineR)  drive(-SPEED / 2, SPEED); // drifted right: turn left
  else if (!onLineL && onLineR)  drive(SPEED, -SPEED / 2); // drifted left: turn right
  else                           drive(0, 0);              // both on black: stop (junction)
}
Notes. You will also need a battery pack (e.g. 2 x 18650 cells) and a black electrical-tape track. Sensor polarity differs between modules - if the robot runs away from the line, swap HIGH/LOW in the sketch.