(+39) 351 838 6453 [email protected]
IT/EN
Home/ Motors/ DC motor control
How-to · Motion control

How to control a DC motor

A brushed DC motor is the opposite of a servo: it does not want a command, it wants energy. Voltage sets how fast it spins, polarity sets which way, and current is the torque you are asking for. Your job is to meter that energy — and that takes a driver between the Arduino and the motor.

2Motor wires
4H-bridge switches
0 – 100 %PWM duty cycle
4×Counts per encoder cycle
The principle

Voltage makes speed, current makes torque

Inside a brushed DC motor there are two nearly linear relationships, and they are all you need to know to control one. First: with no load, speed is proportional to the applied voltage — half the voltage, roughly half the RPM. Second: shaft torque is proportional to the current flowing through the winding.

The two meet in the curve below. The more load you put on the shaft, the more the motor slows down and the more current it draws, all the way to stall: shaft stopped, maximum torque, maximum current. It is the stall current — not the no-load figure printed large on the datasheet — that sizes the driver, the fuse and the wiring, because the motor demands it for an instant at every start and every reversal.

working zone shaft torque → 0 no-load speed stall torque no-load I stall current speed current
Characteristic curve at constant voltage. A motor runs well, and for a long time, inside the highlighted band: no more than a quarter to a third of stall torque. Further right the current climbs, the motor heats up and efficiency collapses. If the load pushes you there, the fix is a higher gear ratio, not a bigger driver.
Direction

Four switches around the motor

To reverse a DC motor you just reverse the polarity across it. The circuit that does this electronically is called an H-bridge, after its shape: two vertical legs, each with one switch to the positive rail and one to ground, and the motor as the crossbar. Close one diagonal pair and current flows through the motor left to right; close the other and it flows the opposite way.

battery V+ GND S1 S2 S3 S4 M Forward — S1 + S4 closed battery V+ GND S1 S2 S3 S4 M Reverse — S2 + S3 closed
The current path is shown in green. In practice the switches are transistors or MOSFETs and you never drive them one by one: the driver exposes two logic inputs (IN1/IN2, or DIR and PWM) and takes care of closing the right pair — and of never closing S1 and S3 together, which would short the battery.

Four states, not two

Besides forward and reverse, an H-bridge can do two more things, and the difference matters when a robot has to stop. When braking the two low switches (or the two high ones) are closed together: the motor terminals are shorted, the back-EMF drives a current that opposes the motion and the shaft stops within a few turns. When coasting everything is open and the motor slows on friction alone. Here is how the states map onto an L298N, the most common teaching driver:

ENAIN1IN2MotorBridge
PWMHIGHLOWForward, speed = duty cycleS1 + S4
PWMLOWHIGHReverse, speed = duty cycleS2 + S3
HIGHLOWLOWFast brakeS3 + S4
HIGHHIGHHIGHFast brakeS1 + S2
LOW××Coast (free-running)all open
Speed

On and off, thousands of times a second

Dropping the voltage with a series resistor would waste as heat all the energy you take away from the motor. The driver does something smarter: it connects and disconnects the full battery at a high frequency. The motor, which cannot follow the individual switching because of its mechanical inertia and winding inductance, responds to the average voltage: the fraction of time the switch is closed — the duty cycle — multiplied by the battery voltage.

Do not confuse this with servo PWM. There, the absolute pulse width is what matters and the frame is fixed at 50 Hz; here only the percentage matters, and the frequency should be high — from a few kHz up to 20 kHz — so the motor does not whine and the current stays smooth.

1 period · 50 µs at 20 kHz duty 25 % ≈ 3 V 3 V duty 50 % ≈ 6 V 6 V duty 75 % ≈ 9 V 9 V 12 V supply · dashed line = average voltage seen by the motor
Same period, three duty cycles. With analogWrite() the Arduino expresses the duty cycle from 0 to 255: 64 ≈ 25 %, 128 ≈ 50 %, 191 ≈ 75 %. The relationship with speed is linear only with no load: under load, and below 10–15 % duty cycle, many motors will not even start.
The 490 Hz whine On an Arduino UNO analogWrite() runs at about 490 Hz (980 Hz on pins 5 and 6): it works, but the motor whines audibly and runs jerkily at low speed. If the driver allows it, raise the frequency by reprogramming a timer — avoiding Timer0, which millis() and delay() depend on, and Timer1 if you also use the Servo library.
The driver

Size it for stall, not for no-load

An Arduino pin supplies about twenty milliamps; even a small gear motor wants hundreds, and several amps when it starts or jams. On top of that, a motor that is back-driven or switched off abruptly sends voltage spikes back that a microcontroller cannot survive. The driver sits in between: logic signals from the Arduino, power from the battery.

Choosing one takes two numbers. The voltage of the battery, with margin — a fully charged 12 V pack is well over 13 V. And the motor's stall current: a 12 V goBILDA Yellow Jacket gear motor draws about 0.25 A with no load and over 9 A at stall. A 2 A driver would spin it happily on the bench and shut down — or burn out — at the first real load.

Driver typeTypical currentInputsWhen to use it
Bipolar H-bridge (L298N)2 A per channelENA + IN1/IN2Small motors for experiments. Loses 2–4 V in the bridge and runs hot: a poor match for 12 V gear motors
MOSFET driver10 – 30 APWM + DIRThe normal choice for 12 V gear motors: negligible voltage drop, PWM up to 20 kHz
Servo-input controllerup to 40 A+1–2 ms pulse at 50 HzDriven like a continuous-rotation servo: 1.5 ms stop, 1.0 and 2.0 ms full speed in each direction
Encoder controller (RoboClaw)2 × 30 ASerial, USB, RC, analogWhen speed and position must be guaranteed: reads the encoders and runs the PID loop on board

The servo-input controller is the most underrated shortcut: it uses exactly the signal described in How to control a hobby servo, so the sketch is written with the Servo library and writeMicroseconds(), with no timers, frequencies or direction pins to think about.

Wiring

Two circuits, one ground

Wiring a DC motor splits cleanly into two worlds. The power circuit — battery, driver, motor — carries amps and needs wire of adequate gauge, kept short, with a fuse close to the battery. The signal circuit — Arduino to driver — carries milliamps and ordinary jumper wires will do.

The two worlds meet at ground: the Arduino's GND must be connected to the driver's GND, otherwise logic HIGH and LOW have no reference. The Arduino itself should be powered separately though, from USB or a dedicated regulator: the motor's current peaks make the battery voltage swing enough to reset it.

Arduino UNO powered from USB D5 D4 GND D2 · D3 H-bridge driver MOSFET · ≥ stall I PWM DIR M+ M− GND VM 12 V battery fused M gear motor with encoder power leads common ground encoder A/B + 5 V + GND → D2, D3 (interrupts)
Typical set-up with a PWM + DIR driver. With an L298N only the names change: ENA instead of PWM, IN1 and IN2 instead of DIR. A motor has no "correct" polarity: if it spins the wrong way, swap M+ and M− or invert the DIR signal in code.
Bench rule Only connect or disconnect the motor with the battery off, and never leave a driver powered without a fuse on the battery. A stalled motor on an unprotected driver is the fastest way to see smoke come out of a circuit board.
Code

The Arduino side

With a PWM + DIR driver it all boils down to one function that takes a signed speed from −255 to +255: the sign picks the direction, the magnitude becomes the duty cycle.

dc_pwm_dir.inoPWM + DIR driver
// DC motor on a PWM + DIR driver, separate 12 V battery,
// driver GND tied to Arduino GND.

const int PIN_PWM = 5;   // PWM output
const int PIN_DIR = 4;

void setup() {
  pinMode(PIN_PWM, OUTPUT);
  pinMode(PIN_DIR, OUTPUT);
}

// speed: -255 (full reverse) ... 0 (stop) ... +255 (full forward)
void motor(int speed) {
  speed = constrain(speed, -255, 255);
  digitalWrite(PIN_DIR, speed >= 0 ? HIGH : LOW);
  analogWrite(PIN_PWM, abs(speed));
}

void loop() {
  motor(128);  delay(2000);   // half speed forward
  motor(0);    delay(500);
  motor(-128); delay(2000);   // half speed reverse
  motor(0);    delay(500);
}

An L298N takes three inputs, and in return you get the distinction between braking and coasting, exactly as in the state table above.

l298n.inoENA + IN1 / IN2
const int ENA = 5;   // PWM — remove the ENA jumper on the board
const int IN1 = 7;
const int IN2 = 8;

void setup() {
  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
}

void forward(int pwm) { digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);  analogWrite(ENA, pwm); }
void reverse(int pwm) { digitalWrite(IN1, LOW);  digitalWrite(IN2, HIGH); analogWrite(ENA, pwm); }
void brake()          { digitalWrite(IN1, LOW);  digitalWrite(IN2, LOW);  digitalWrite(ENA, HIGH); }
void coast()          { digitalWrite(ENA, LOW); }

void loop() {
  forward(200); delay(1500);
  brake();      delay(800);    // stops within a few turns
  reverse(200); delay(1500);
  coast();      delay(800);    // slows down on inertia
}

Never reverse instantly

Going from +255 to −255 in one step means putting almost twice the battery voltage across the motor — its back-EMF plus the reversed battery — with a current above stall. The driver trips its protection, the gears take a hit and the battery sags. A ramp of a few hundred milliseconds fixes all of it.

ramp.inoLimited acceleration
int current = 0;            // speed applied right now
const int STEP = 5;        // maximum change per call

// Call every 10 ms: 0 to 255 takes about 0.5 s.
void towardTarget(int target) {
  if      (current < target) current = min(current + STEP, target);
  else if (current > target) current = max(current - STEP, target);
  motor(current);                // the function from dc_pwm_dir.ino
}
Feedback

PWM sets the voltage, not the speed

Everything so far is open-loop control: you ask for 50 % and hope. Under load, uphill or on a draining battery, the same duty cycle gives fewer RPM, and two "identical" motors never spin at exactly the same speed — which is why a two-wheel robot driven at fixed PWM never goes straight.

A gear motor with an encoder closes the circle. On the motor shaft, before the gearbox, a magnetic disc and two Hall sensors produce two square waves, A and B, a quarter period apart. Counting the edges tells you how far the shaft has turned; seeing which channel leads tells you which way.

A B 1 2 3 4 1 cycle = 4 counts A leads B → forward · B leads A → reverse
Counting every edge on both channels (4× decoding), an encoder with 7 pulses per revolution gives 28 counts per motor revolution. After the gearbox you multiply by the ratio: on a 19.2:1 gear motor that is about 537.7 counts per output-shaft revolution, or two thirds of a degree per count.

On an Arduino UNO only pins 2 and 3 have dedicated interrupts, and that is where the two channels go: at a few thousand RPM the edges arrive too fast to read in loop(). Each interrupt compares the two channels and updates a signed counter.

encoder_rpm.ino4× quadrature · RPM
const int ENC_A = 2;   // interrupt pins
const int ENC_B = 3;
const float COUNTS_PER_REV = 537.7;   // 28 x 19.2 — output shaft

volatile long counts = 0;

void edgeA() { counts += (digitalRead(ENC_A) != digitalRead(ENC_B)) ? 1 : -1; }
void edgeB() { counts += (digitalRead(ENC_A) == digitalRead(ENC_B)) ? 1 : -1; }

void setup() {
  Serial.begin(115200);
  pinMode(ENC_A, INPUT_PULLUP);
  pinMode(ENC_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(ENC_A), edgeA, CHANGE);
  attachInterrupt(digitalPinToInterrupt(ENC_B), edgeB, CHANGE);
}

long previous = 0;

void loop() {
  delay(100);                      // 100 ms measuring window
  noInterrupts();
  long now = counts;               // atomic copy of the counter
  interrupts();

  float revs = (now - previous) / COUNTS_PER_REV;
  float rpm  = revs * 600.0;          // 100 ms -> 1 minute
  previous = now;

  Serial.print("position: "); Serial.print(now / COUNTS_PER_REV * 360.0);
  Serial.print(" deg   rpm: "); Serial.println(rpm);
}

Closing the loop

With the measured speed you can correct the PWM: if the motor is slower than the target you raise the duty cycle, if it is faster you lower it. The snippet below is the simplest form — an integral controller — and it is already enough to hold a wheel at constant speed as the load changes. Positioning an arm precisely needs a full PID, or a controller such as RoboClaw that runs one on board.

constant_speed.inoSpeed loop
const float TARGET_RPM = 150.0;
const float KI = 0.4;        // gain: raise it until it oscillates
float pwm = 0;

// Call right after computing rpm, every 100 ms.
void regulate(float rpm) {
  float error = TARGET_RPM - rpm;
  pwm = constrain(pwm + KI * error, -255, 255);
  motor((int)pwm);
}
Troubleshooting

When it misbehaves

SymptomTypical causeFix
Arduino resets when the motor startsArduino powered from the motor battery with no dedicated regulatorPower the Arduino from USB or a separate regulator; grounds tied
Motor does not move, driver is poweredNo common ground, or ENA left on its jumperTie Arduino and driver GND; remove the jumper and wire ENA to a PWM pin
Hums but will not start at low PWMDuty cycle below the start-up thresholdSet a minimum (e.g. 40/255) or use a higher gear ratio
Constant high-pitched whinePWM frequency in the audible band (490–980 Hz)Raise the PWM frequency if the driver allows it
Driver runs hot or tripsStall current above its rating, or abrupt reversalsStronger driver, acceleration ramp, higher gear ratio
Slower than expected on an L298N2–4 V drop across the bipolar transistorsMOSFET driver
Encoder counts backwardsChannels A and B swapped relative to motor directionSwap ENC_A and ENC_B in code, or flip the sign
Encoder misses countsChannels polled in loop() instead of using interruptsUse pins 2 and 3 with attachInterrupt()
FAQ

Frequently asked questions about DC motor control

Can I connect a DC motor directly to an Arduino pin?

No. An Arduino pin supplies 20–40 mA at most, while even a small gear motor draws hundreds of milliamps and several amps at stall. On top of that, a spinning motor generates reverse voltages that damage the microcontroller. You always need an H-bridge driver between the Arduino and the motor.

How do you control the speed of a DC motor?

With PWM: the driver switches the supply voltage on and off thousands of times per second, and the motor, which cannot follow the individual switching because of its inertia and inductance, behaves as if it were fed the average voltage. At 50 % duty cycle on 12 V the motor runs roughly as it would on 6 V.

How do you reverse the direction of a DC motor?

By reversing the polarity across its terminals. An H-bridge does this with four electronic switches: closing one diagonal pair drives current through the motor one way, closing the other pair drives it the opposite way. On the Arduino side you only need a direction pin, or a combination of two inputs IN1 and IN2.

How do I choose a driver for my DC motor?

Look at the motor's stall current, not its no-load current: it is what the motor draws at start-up and whenever it jams, and the driver has to survive it at least briefly. Then the voltage: the driver must accept the battery voltage with margin. An L298N is fine for 1–2 A hobby motors; 12 V gear motors stalling at 5–10 A need a MOSFET driver or a controller such as RoboClaw.

What is the difference between braking and coasting?

When braking, the H-bridge shorts the two motor terminals together: the back-EMF drives a current that opposes the motion and the shaft stops quickly. When coasting, the bridge opens every switch and the motor slows down on friction alone. On an L298N you brake with IN1 = IN2 and EN high, and coast by pulling EN low.

What is the encoder on a gear motor for?

To know how far and how fast the shaft is really turning. PWM sets the voltage, not the speed: under load or on a flat battery the motor slows down. Counting the pulses from the quadrature encoder gives you position, direction and RPM, and lets you close a control loop that corrects the PWM.

From our catalogue

DC motors & controllers at StepLab

The code is the easy part. The hard part is choosing a motor with the right output-shaft speed, a driver that survives its stall current and a solid way to mount it to the structure. In the catalogue you will find goBILDA and ServoCity gear motors with and without encoders, planetary and spur, and the controllers to drive them.

DC motors & controllers, ready to ship

No-load speed, torque and stall current are listed on every product page. Not sure which motor or driver your project needs? Ask us: we answer with part numbers, not brochures.