PID motor speed control with an encoder on Arduino: design worksheet and code

A ₹1,830 design worksheet for holding a DC gear motor at a set speed with an encoder and a PID loop, with the counts-to-RPM maths, anti-windup and a tuning order.

About the author · Editorial & verification standards

  • Parts₹1,830
  • Bench time5–8 h
  • LevelIntermediate
  • ReviewedNov 2026

A ₹1,830 speed controller that keeps a DC gear motor at a chosen RPM even when the load or the battery changes. An encoder counts shaft pulses, the sketch turns the counts into RPM every 100 ms, and a PID loop adjusts the PWM. It is the building block under straight-line driving, conveyors and wheel-speed control.

Scope: intermediate. This is a design worksheet with illustrative costs. It has not been bench-tested by this site. The counts-to-RPM table was computed by script, using an example motor with 11 pulses per motor turn and a 30:1 gearbox (330 counts per output turn). Your motor’s numbers are on its listing or can be found by turning the shaft by hand. The gains in the sketch are starting guesses and must be tuned.

How it works

If the encoder gives 330 counts per turn of the output shaft and the sketch counts for 0.1 second, then RPM = counts × 10 × 60 / 330 = counts × 600 / 330. At 100 RPM that is 55 counts in each 100 ms window. One count of difference is therefore about 1.8 RPM, which is the resolution of the measurement at this sample time; a longer window gives finer resolution but slower response.

The controller compares the target RPM with the measured RPM. The error times Kp gives the immediate push; the running sum of error times Ki removes any steady shortfall; the sum is limited so it cannot wind up while the motor is saturated at full PWM. Derivative is left at zero because the count measurement is coarse and the derivative would amplify its noise.

Bill of materials

PartQtyUnitTotal
Arduino Uno R3 (or compatible)1₹550₹550
12 V geared DC motor with quadrature encoder1₹700₹700
L298N motor driver board1₹180₹180
12 V battery pack or adapter1₹250₹250
Motor bracket and wheel or load disc1₹100₹100
Jumper wires1₹50₹50
Parts total₹1,830

Scroll the table sideways to see every column.

Prices checked Nov 2026. Shipping and tools are not included.

Prices are illustrative figures for Indian sellers in November 2026, before shipping, and have not been checked against current listings.

The numbers

SpeedCounts per 100 msOne-count error
20 RPM11.01.8 RPM
50 RPM27.51.8 RPM
100 RPM55.01.8 RPM
150 RPM82.51.8 RPM
200 RPM110.01.8 RPM
RPM = counts × 600 / 330 for a 100 ms window and 330 counts per turn. Fractions of a count appear as the count alternating between neighbouring whole numbers.

With Kp = 0.8 an error of 20 RPM adds 16 PWM steps, and Ki = 2 adds 40 PWM steps for every second the error stays at 20 RPM. These are starting values: the right gains depend on the motor, supply and load.

Power and wiring

PartConnects toNote
Encoder A channelD2 (interrupt)Counts every rising edge
Encoder B channelD3Not used for speed alone; wire it for direction later
Encoder VCC and GND5V and GNDCheck your encoder’s voltage
L298N ENA / IN1 / IN2D5 / D7 / D8Motor
BatteryL298N 12V inputJoin the Uno GND to the L298N GND
Check the motor and encoder wire colours against the listing before powering; reversed encoder supply can damage the encoder board.

The sketch

// PID motor speed control: Uno + L298N + encoder motor
// Design worksheet: CPR and gains are examples; set your own.

const int ENC_A = 2;
const int EN = 5, IN1 = 7, IN2 = 8;
const float CPR = 330.0;            // counts per output turn (example)
const unsigned long DT = 100;       // ms per control step

float target = 100;                 // RPM
float Kp = 0.8, Ki = 2.0;
float integral = 0;
volatile long counts = 0;
unsigned long lastStep = 0;

void onPulse() { counts++; }

void setup() {
  pinMode(EN, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);
  pinMode(ENC_A, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(ENC_A), onPulse, RISING);
  Serial.begin(115200);
}

void loop() {
  unsigned long now = millis();
  if (now - lastStep < DT) return;
  lastStep = now;

  noInterrupts(); long c = counts; counts = 0; interrupts();
  float rpm = c * (60000.0 / DT) / CPR;

  float error = target - rpm;
  integral += error * (DT / 1000.0);
  integral = constrain(integral, -255.0 / Ki, 255.0 / Ki);   // anti-windup
  float out = Kp * error + Ki * integral;
  out = constrain(out, 0, 255);
  analogWrite(EN, (int)out);

  Serial.print(target); Serial.print(' ');
  Serial.print(rpm);    Serial.print(' ');
  Serial.println(out);
}

The three printed numbers (target, measured, output) can be viewed together on the Serial Plotter, which is the easiest way to see overshoot and settling. A real build may also want a short ramp on the target to avoid a violent start. The sketch has been proofread but not compiled on this site.

Test plan

  1. Count a turn: turn the output shaft one full turn by hand and print the counts. Set CPR to what you see.
  2. Open loop: run a fixed PWM and print the RPM to learn the motor’s range on your supply.
  3. Step response: set Ki to 0, raise Kp until it responds quickly without ringing, then add Ki until the steady error disappears.
  4. Disturbance: press a finger lightly on the wheel and see how fast the speed recovers.
  5. Battery sag: repeat with a part-discharged pack and compare.
  6. Low speed: try 20 RPM and note whether the 1.8 RPM resolution is acceptable.

What usually goes wrong

SymptomLikely causeFix
RPM reads zeroEncoder not powered or wired to the wrong pinCheck D2 and the encoder supply
Speed oscillatesGains too highLower Kp and Ki
Never reaches targetTarget above what the supply can deliver, or integral limitedCheck the open-loop maximum
Noisy RPMCoarse counts at low speedLengthen the window or use period measurement
Motor runs backwardsMotor wires reversedSwap the motor wires or the IN pins

Upgrades

  • Direction: use channel B to detect direction.
  • Two wheels: run two loops for straight-line driving.
  • Position control: count to a target for precise moves.
  • Feed-forward: add a PWM guess from the target to speed up response.

Cost and parts notes

The ₹1,830 total is an illustration and does not include shipping. Use the cost calculator to compare sellers.

Common questions

Why use an interrupt for the encoder?

Pulses can arrive faster than the main loop would check them. The interrupt counts each one.

What is anti-windup?

Limiting the integral sum so it does not keep growing while the output is stuck at its limit.

Why is derivative zero?

Counts are coarse, so a derivative term mostly amplifies noise. Many speed loops work with only P and I.

How do I choose the sample time?

A shorter window responds faster but has coarser RPM resolution; 50 to 100 ms is a common starting range.

Last reviewed: November 2026. This is a design worksheet with illustrative costs. It has not been bench-tested by this site; library names, pins and limits must be checked against your board and the current library versions, and measurements from your build are welcome.

More builds

Next builds to try

Free: the final-year project pack

A shortlist with BOMs, a report outline that matches the usual chapter scheme, a costing sheet and 40 viva questions. Built for the February–April submission season.

The Build Note

One short email when something is worth your bench time.

A new build sheet, a part price that moved, or a mistake worth avoiding. No daily drip, no recycled news.

One short email when a build or a price is worth your time. Unsubscribe in one click.