PinoutSearch

Drive Two DC Motors (L298N + Arduino)

Run two DC motors forward, backward, and at variable speed with an L298N H-bridge — the drivetrain for a robot car.

Intermediate30 min

What you need

Wiring

Hover a pin or a wire to trace the connection.

Code

l298n.ino
// Drive two DC motors forward, then reverse, then stop.
const int ENA = 9, IN1 = 8, IN2 = 7;   // motor A
const int ENB = 3, IN3 = 5, IN4 = 4;   // motor B

void setup() {
  int pins[] = {ENA, IN1, IN2, ENB, IN3, IN4};
  for (int p : pins) pinMode(p, OUTPUT);
}

void loop() {
  // both forward at ~70% speed
  digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENA, 180);
  digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); analogWrite(ENB, 180);
  delay(2000);
  // both reverse
  digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH);
  delay(2000);
  // stop
  analogWrite(ENA, 0); analogWrite(ENB, 0);
  delay(1000);
}

Steps

  1. Wire ENA/IN1/IN2 (motor A) to D9/D8/D7 and ENB/IN3/IN4 (motor B) to D3/D5/D4.
  2. Motor A to OUT1/OUT2, motor B to OUT3/OUT4.
  3. Power motors from a 6–12V supply on +12V; share ground with the Arduino.
  4. Upload — both motors go forward, reverse, then stop. Swap a motor's leads if it spins the wrong way.