Home › DIY Projects › Motor Speed Control

DC Motor Speed and Direction Control with Arduino and L298N

Make a motor speed up, slow down and reverse with code. This is the first step to building your own robot car.

  • Level: Beginner
  • Time: 40 minutes
  • Board: Arduino Uno
  • No soldering
▶ Copy code + open simulatorGet the code

Watch it in action

Subscribe to ZEENAIX on YouTube for more projects

What you will build

An Arduino cannot power a motor directly: its pins give only a tiny current. The L298N motor driver sits in between. Two direction pins (IN1, IN2) choose forward or backward, and a PWM pin (ENA) sets the speed from 0 to 100%.

The sketch runs a demo on its own: the motor speeds up forward, slows down, stops, then does the same in reverse. Type f, b, s or a number 0–9 in the Serial Monitor to take control yourself. You will learn how an H-bridge works, how analogWrite() PWM controls speed, and why the motor needs its own battery.

Components required

Arduino Uno R3 compatible boardArduino Uno R3 × 1The brain. Any Uno or Nano works.
View in store →
L298N dual H-bridge motor driver moduleL298N motor driver × 1Lets the Arduino control a motor safely.
View in store →
BO gear motor (3–6V) × 1The yellow motor used in robot cars.
View in store →
9V
9V battery × 1Powers the motor. Use a battery clip.
View in store →
Jumper wires (male to male) × 10About 10 wires.
View in store →

Circuit diagram and connections

Tap any part in the diagram to see what it does and where it connects.

Arduino Uno578GND L298NENAIN1IN2+12VGNDGNDOUT Motor 9V+− Purple = ENA (speed) · Green = IN1 · Yellow = IN2 · Red = battery + · Black = GND (shared)

Tap a part to learn more.

Part pinArduino pinWire colour (suggested)
L298N ENA (jumper removed)D5 (PWM)Purple
L298N IN1D7Green
L298N IN2D8Yellow
L298N GNDGND (and battery −)Black
L298N +12V (VS)Battery + (not the Arduino)Red
L298N OUT1 / OUT2Motor wiresAny

Arduino code

Copy this sketch into the simulator or the Arduino IDE. It needs no extra libraries. We wrote and tested it ourselves; you are free to use and change it.

/*
  ZEENAIX DIY Project: DC Motor Speed and Direction Control with Arduino and L298N
  https://zeenaix.com/diy-projects/motor-speed-control-arduino/

  Parts: Arduino Uno, L298N motor driver, BO gear motor (3-6V),
         9V battery (or 4 x AA) for the motor, jumper wires.

  Wiring (L298N channel A):
    ENA -> pin 5 (PWM, remove the ENA jumper)   IN1 -> pin 7   IN2 -> pin 8
    OUT1 / OUT2 -> motor wires
    +12V (VS) -> battery +   GND -> battery - AND Arduino GND (common ground)

  What it does:
    Runs a demo: speeds up forward, slows down, stops, then does the same in
    reverse. Type a command in the Serial Monitor (9600 baud) to take over:
      f = forward   b = backward   s = stop   0..9 = speed (0 = off, 9 = full)
*/

const int ENA = 5;   // speed (PWM)
const int IN1 = 7;   // direction
const int IN2 = 8;   // direction

int  speedPwm = 0;        // 0..255
int  direction = 0;       // 1 = forward, -1 = backward, 0 = stop
bool demo = true;         // demo runs until you send a command

void apply() {
  digitalWrite(IN1, direction > 0 ? HIGH : LOW);
  digitalWrite(IN2, direction < 0 ? HIGH : LOW);
  analogWrite(ENA, direction == 0 ? 0 : speedPwm);
  Serial.print(direction > 0 ? "FORWARD" : direction < 0 ? "BACKWARD" : "STOP");
  Serial.print("  speed ");
  Serial.print(direction == 0 ? 0 : (long)speedPwm * 100 / 255);
  Serial.println("%");
}

// Waits, but stops the demo as soon as you type something (returns false)
bool wait(unsigned long ms) {
  unsigned long start = millis();
  while (millis() - start < ms) {
    if (Serial.available()) { demo = false; return false; }
  }
  return true;
}

// Changes the speed step by step so the motor starts and stops smoothly
bool ramp(int from, int to) {
  int step = (to > from) ? 15 : -15;
  for (int p = from; (step > 0) ? p <= to : p >= to; p += step) {
    speedPwm = p;
    apply();
    if (!wait(150)) return false;
  }
  return true;
}

void setup() {
  Serial.begin(9600);
  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  Serial.println("ZEENAIX Motor Control ready. Send f, b, s or 0-9.");
}

void loop() {
  if (Serial.available()) {
    demo = false;
    char c = Serial.read();
    if (c == 'f') direction = 1;
    else if (c == 'b') direction = -1;
    else if (c == 's') direction = 0;
    else if (c >= '0' && c <= '9') speedPwm = (c - '0') * 255 / 9;
    else return;                      // ignore newlines and other keys
    if (direction != 0 && speedPwm == 0) speedPwm = 255;
    apply();
  }
  if (demo) {
    direction = 1;  if (!ramp(60, 255) || !ramp(255, 60)) return;
    direction = 0;  apply(); if (!wait(1000)) return;
    direction = -1; if (!ramp(60, 255) || !ramp(255, 60)) return;
    direction = 0;  apply(); if (!wait(1000)) return;
  }
}

Step-by-step instructions

A. Try it in the free simulator (5 minutes)

  1. Open the ZEENAIX Arduino Simulator and choose Blank editor with the Arduino Uno board. You can also open the ready DC Motor Control (L293D) example: the L293D chip works the same way as the L298N.
  2. Paste the sketch from the code section in place of the starter code.
  3. Connect the driver: ENA to pin 5, IN1 to pin 7 and IN2 to pin 8, as in the table.
  4. Press the green ▶ run button and open Serial. You will see FORWARD speed 23% climbing to 100%, then down, then STOP and BACKWARD.
  5. Type b and then 5 in the Serial input box: the output changes to BACKWARD speed 55%. Type s to stop.

B. Build it for real (35 minutes)

  1. Take the small black jumper off the ENA pins of the L298N, so the Arduino can control the speed.
  2. Screw the two motor wires into OUT1 and OUT2.
  3. Connect the 9V battery: + to the +12V terminal and − to GND. Add a rocker switch in the + wire if you have one.
  4. Join the L298N GND to an Arduino GND. Without this shared ground the motor will not respond.
  5. Connect ENA to pin 5, IN1 to pin 7 and IN2 to pin 8 with jumper wires.
  6. Upload the code from the Arduino IDE (Tools › Board › Arduino Uno), switch on the battery and open the Serial Monitor at 9600 baud. Watch the demo, then type commands to drive the motor yourself.

Try it here: what the motor will do

STOP speed 0%

Same rules as the sketch: a number from 0 to 9 sets the speed (9 = 100%), f and b set the direction.

How it works

Inside the L298N is an H-bridge: four switches around the motor, arranged like the letter H. Turning on one diagonal pair lets current flow one way through the motor (forward). The other pair sends it the other way (backward). IN1 and IN2 choose the pair: HIGH/LOW is forward, LOW/HIGH is backward, LOW/LOW is stop.

Speed comes from PWM (pulse-width modulation). analogWrite(ENA, 128) switches the motor on and off about 980 times a second, on for half of each cycle, so it gets about half the power. 255 is always on (100%), 0 is off. The motor is too slow to follow each pulse, so it just runs at an in-between speed.

Tested: we compiled this sketch for the Arduino Uno (zero warnings) and ran it in an AVR simulation while measuring the real pin signals. The demo ramped the ENA duty cycle from 23% to 100% and back with IN1 HIGH (forward), then stopped with both pins LOW. Typing b switched IN2 HIGH (backward), 5 set the duty cycle to 55%, and s stopped the motor, exactly as printed on the Serial Monitor.

Real-life uses of motor speed control

Robot car

Two motors, one L298N: drive both forward to go straight, or one forward and one backward to spin on the spot.

Fan speed controller

Control a small DC fan by temperature: faster when it is hot, slow when it is cool.

Conveyor belt model

A slow, steady motor moves items along a belt for a factory or sorting machine project.

Automatic curtain or window

Run the motor forward to open and backward to close, with limit switches at each end.

Mini drill or grinder speed

The same PWM idea sets the speed of hobby tools so they do not run too fast.

Troubleshooting

  • Motor does not move: check the shared GND between the Arduino and the L298N, and that the ENA jumper is removed and ENA goes to pin 5.
  • Motor only runs at full speed: the ENA jumper is still on. Remove it so pin 5 can control the speed.
  • Motor hums but does not turn at low speeds: below about 25% the motor may not have enough power to start. Use a higher minimum speed.
  • Battery dies quickly: 9V batteries are small. For longer runs use 4 × AA cells or a 2-cell Li-ion pack (with proper protection).

Frequently asked questions

Why not connect the motor straight to the Arduino?

A motor can draw hundreds of milliamps, but an Arduino pin gives only about 20 mA. It would damage the pin and the motor would not run.

Can I control two motors?

Yes. The L298N has two channels. Use ENB, IN3 and IN4 for the second motor, for example on pins 6, 9 and 10.

Why does the 9V battery not power the Arduino here?

It can, through the L298N 5V output, but motors cause voltage dips that can reset the Arduino. For learning, power the Arduino from USB and the motor from the battery.

Do I need to buy parts to try this?

No. You can run the whole project in the free ZEENAIX simulator first, then buy only the parts you need when you are ready to build it.

Build it for real

Get the Arduino Uno, L298N motor driver, BO gear motor, 9V battery, on/off switch and jumper wires from the ZEENAIX store, with delivery across India.

▶ Copy code + open simulatorMore DIY projects