Line follower: bang-bang, then PD
A two-wheel robot follows black tape round a 1.6 m oval: first bang-bang, which zigzags and loses the line on the bends, then PD on the line's position from…
Control · Advanced
In a real product: Line-following robot (Robotics): Warehouse carts and hospital delivery robots follow lines on the floor: the steering loop decides how fast they can go.
A line follower is a control loop you can see. Five IR sensors across the robot's front read the floor: over the white mat little comes back, over black tape a lot less, so each one's output rises over the tape. The firmware works out where the line is and steers the two wheels to keep it in the middle. Open the World tool's Arena view to watch the robot from above, its sensors' beams and its trail.
What you'll learn
- Wiring a robot like a real one: a TB6612FNG between the board and the two gear motors, the battery on the driver's VM
- Bang-bang steering, and why it zigzags and loses the line on a bend
- The line's position as the readings' weighted mean, a number in millimetres instead of five yes-or-nos
- PD steering: proportional to the position, with a derivative to damp the swing
- Tuning a loop live, and the trade between speed and staying on the line
How it works
The robot is one part: two 6 V gear motors (1:30, about 300 rpm at the 42 mm wheels, 0.65 m/s), a five-channel IR array 12 mm apart, an ultrasonic sensor and wheel encoders. Its own 4 × AA pack is on VM, wired to the driver's motor supply; the Uno drives the driver's inputs and PWM pins.
Each IR reading goes from about 61 over the mat to 921 over the tape, and in between when the 19 mm tape covers part of a sensor's spot. The sketch scales each to 0–1 and takes the weighted mean of the sensors' places (+24, +12, 0, −12, −24 mm), which gives the line's position under the array, smoothly, to a fraction of a millimetre.
Bang-bang (send b) turns hard toward the line whenever it is more than 4 mm off. It works on the straights, but each correction overshoots, and on a bend it swings off the tape. PD (p, the default) steers by u = Kp·pos + Kd·(pos − last): the left wheel gets base − u, the right base + u. The derivative is how fast the line moves under the array, and it brakes the turn before the robot overshoots. At base 180 it laps the oval in about 3.7 s without ever losing the tape.
Try this
- Run it, open the World tool's Arena view and watch the HUD: laps, the last lap's time and time off the line.
- Send
b: the bang-bang robot zigzags down the straight and runs off the tape on the bend. Sendpto rescue it. - Set
kd=0with the Kd slider: the robot snakes along the line. How much Kp alone can it take before it oscillates? - Raise
base(sendbase=220): faster laps, until the robot runs wide on the bends. What lap time can you reach while staying on the tape? The Line-follower race challenge asks for three laps in under 18 s. - Change the arena's scene to line-sharp or line-figure8 and try the same gains.
sketch.ino
// Line follower: a two-wheel robot on a 1.6 m oval of black tape, through a TB6612FNG.
// Left motor: AIN1 7, AIN2 8, PWMA 5. Right motor: BIN1 10, BIN2 11, PWMB 6. STBY 9.
// IR1..IR5 (left to right, 12 mm apart) on A0..A4: about 61 over the white mat, 921 over the tape.
// Serial: "b" steers bang-bang, "p" PD (the default); kp=, kd= and base= set the gains and the cruising duty.
const int AIN1 = 7, AIN2 = 8, PWMA = 5, BIN1 = 10, BIN2 = 11, PWMB = 6, STBY = 9;
const int IR[5] = {A0, A1, A2, A3, A4};
const int WHITE = 61, BLACK = 921;
float kp = 12.0, kd = 150.0; // duty per mm off the line, and per mm it moved in 5 ms
int base = 180; // cruising duty out of 255
bool bang = false;
float lastPos = 0;
unsigned long lastRun = 0, lastPrint = 0;
void motor(int in1, int in2, int pwm, int duty) {
duty = constrain(duty, -255, 255);
digitalWrite(in1, duty >= 0 ? HIGH : LOW);
digitalWrite(in2, duty >= 0 ? LOW : HIGH);
analogWrite(pwm, abs(duty));
}
// Where the line is under the array, in mm (+ to the left): the readings' weighted mean, each sensor's place times
// how much of the tape it sees. With no sensor on the tape: the side it was last seen, as far out as the array goes.
float linePosition() {
float sum = 0, weighted = 0;
for (int i = 0; i < 5; i++) {
float c = constrain((analogRead(IR[i]) - WHITE) / float(BLACK - WHITE), 0.0, 1.0);
sum += c;
weighted += c * (2 - i) * 12.0;
}
return sum > 0.2 ? weighted / sum : (lastPos > 0 ? 30 : -30);
}
void readCommands() {
if (!Serial.available()) return;
String c = Serial.readStringUntil('\n');
c.trim();
if (c == "b") bang = true;
else if (c == "p") bang = false;
else if (c.startsWith("kp=")) kp = c.substring(3).toFloat();
else if (c.startsWith("kd=")) kd = c.substring(3).toFloat();
else if (c.startsWith("base=")) base = constrain(c.substring(5).toInt(), 0, 255);
}
void setup() {
Serial.begin(115200);
Serial.setTimeout(5);
pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT); pinMode(PWMA, OUTPUT);
pinMode(BIN1, OUTPUT); pinMode(BIN2, OUTPUT); pinMode(PWMB, OUTPUT);
pinMode(STBY, OUTPUT);
digitalWrite(STBY, HIGH);
}
void loop() {
readCommands();
unsigned long now = millis();
if (now - lastRun >= 5) {
lastRun = now;
float pos = linePosition();
int l, r;
if (bang) {
// Full ahead near the middle, a hard turn toward the line otherwise.
l = pos > 4 ? base * 3 / 10 : base;
r = pos < -4 ? base * 3 / 10 : base;
} else {
float u = kp * pos + kd * (pos - lastPos);
l = base - u;
r = base + u;
}
lastPos = pos;
motor(AIN1, AIN2, PWMA, l);
motor(BIN1, BIN2, PWMB, r);
}
if (now - lastPrint >= 100) {
lastPrint = now;
Serial.print("pos:"); Serial.println(lastPos, 1);
}
}