Try Embedded

Two-wheel robot drive (TB6612FNG)

Drive a two-wheeled robot's motors through a TB6612FNG: forward, spin on the spot, brake and coast, with PWM speed.

Motors · Intermediate

In a real product: Robot vacuum (Robotics): Two wheel motors drive and steer.

A two-wheeled robot steers by running its wheels at different speeds. A TB6612FNG holds two H-bridges, one per motor: two pins set each motor's direction and a PWM pin its speed. Unlike the older L298N it uses MOSFETs, so it wastes far less of the battery as heat.

What you'll learn

  • An H-bridge's four states: forward, reverse, short brake (both outputs LOW) and coast (both off)
  • A small motion API, drive(left, right), from −255 to 255, hiding the pins
  • Why STBY must be HIGH, and why braking stops a motor faster than coasting

How it works

For each motor, IN1 HIGH and IN2 LOW turn it one way and the reverse the other way; the PWM pin's duty sets how much of the time the bridge drives, so analogWrite(PWMA, 128) is about half speed. With both inputs HIGH the bridge shorts the motor's terminals (a brake); with both LOW it lets go (the motor coasts). The sketch runs a little routine: forward, spin right, forward slowly, brake, then coast.

Try this

  • Watch both motors' rpm under the canvas as the routine runs. Spinning on the spot is one wheel each way.
  • Leave STBY unwired: nothing turns. Its input reads LOW when left open.
  • Add a turn(degrees) that spins for a time proportional to the angle.

sketch.ino

// A two-wheel drive on a TB6612FNG: motor A (left) on AIN1 7, AIN2 8, PWMA 5; motor B (right) on BIN1 12, BIN2 13,
// PWMB 6; STBY on 4. A routine: forward, spin, slow forward, brake, coast, again.
const int STBY = 4, PWMA = 5, AIN1 = 7, AIN2 = 8, PWMB = 6, BIN1 = 12, BIN2 = 13;
const int DIRECTION_PINS[] = {AIN1, AIN2, BIN1, BIN2};
const int OUTPUTS[] = {STBY, PWMA, AIN1, AIN2, PWMB, BIN1, BIN2};

// One motor: speed from -255 (full reverse) to 255 (full forward).
void motor(int in1, int in2, int pwm, int speed) {
  digitalWrite(in1, speed > 0);
  digitalWrite(in2, speed < 0);
  analogWrite(pwm, min(abs(speed), 255));
}

void drive(int left, int right) {
  motor(AIN1, AIN2, PWMA, left);
  motor(BIN1, BIN2, PWMB, right);
}

void brake() {
  for (int pin : DIRECTION_PINS) digitalWrite(pin, HIGH);
}

void setup() {
  Serial.begin(9600);
  for (int pin : OUTPUTS) pinMode(pin, OUTPUT);
  digitalWrite(STBY, HIGH);
}

void loop() {
  Serial.println("forward");
  drive(200, 200);
  delay(1500);
  Serial.println("spin right");
  drive(160, -160);
  delay(800);
  Serial.println("slow forward");
  drive(90, 90);
  delay(1500);
  Serial.println("brake");
  brake();
  delay(600);
  Serial.println("coast");
  drive(0, 0);
  delay(1000);
}

Lessons behind it