Try Embedded

DC motor speed and direction

Control a DC motor's speed with PWM and its direction with an L298N H-bridge.

Motors · Intermediate

In a real product: Electric window (Automotive): An H-bridge drives the window motor up and down.

A DC motor spins one way or the other depending on which way current flows through it, and faster the more voltage it gets. An H-bridge can reverse the current, and switching it with PWM sets the speed. The L298N module has two.

What you'll learn

  • How an H-bridge reverses a motor with four switches
  • Speed control with PWM on the enable pin
  • Ramping speed up and down smoothly

How it works

IN1 and IN2 (pins 7 and 8) set the direction: IN1 high and IN2 low drives OUT1 high and OUT2 low, so current flows one way; the other way round reverses it. Both the same (both low or both high) stops the motor.

ENA (pin 9) enables the bridge. analogWrite(9, speed) switches it on and off quickly, so the motor gets power for speed / 255 of the time and turns at that fraction of its full speed. The motor's label shows its speed in rpm.

On real hardware the motor supply goes to the 12V terminal (and the grounds are joined). Remove the ENA jumper before wiring ENA to a pin.

Try this

  • Control the speed with a potentiometer and the direction with a switch.
  • Use bridge B (IN3, IN4, ENB, OUT3, OUT4) to add a second motor and make a two-wheeled robot turn.
  • Brake by setting IN1 and IN2 both high, and compare with coasting (ENA low).

sketch.ino

// A DC motor on an L298N: ENA (speed) on pin 9, IN1 and IN2 (direction) on pins 7 and 8.
const int ENA = 9, IN1 = 7, IN2 = 8;

// speed from -255 (full reverse) to 255 (full forward); 0 stops.
void drive(int speed) {
  digitalWrite(IN1, speed > 0 ? HIGH : LOW);
  digitalWrite(IN2, speed < 0 ? HIGH : LOW);
  analogWrite(ENA, abs(speed));
}

void setup() {
  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println("Speeding up forward");
  for (int s = 0; s <= 255; s += 5) { drive(s); delay(40); }
  delay(1000);
  Serial.println("Slowing down");
  for (int s = 255; s >= 0; s -= 5) { drive(s); delay(40); }
  Serial.println("Reverse at half speed");
  drive(-128);
  delay(2000);
  Serial.println("Stop");
  drive(0);
  delay(1000);
}

Lessons behind it