# 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.

Canonical: https://roboticsengineering.in/projects/pid-motor-speed-control-encoder-arduino/ | Published: 2026-11-04 | Updated: 2026-11-04

**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

| Part | Qty | Unit | Total |
| --- | --- | --- | --- |
| Arduino Uno R3 (or compatible) | 1 | ₹550 | ₹550 |
| 12 V geared DC motor with quadrature encoder | 1 | ₹700 | ₹700 |
| L298N motor driver board | 1 | ₹180 | ₹180 |
| 12 V battery pack or adapter | 1 | ₹250 | ₹250 |
| Motor bracket and wheel or load disc | 1 | ₹100 | ₹100 |
| Jumper wires | 1 | ₹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

| Speed | Counts per 100 ms | One-count error |
| --- | --- | --- |
| 20 RPM | 11.0 | 1.8 RPM |
| 50 RPM | 27.5 | 1.8 RPM |
| 100 RPM | 55.0 | 1.8 RPM |
| 150 RPM | 82.5 | 1.8 RPM |
| 200 RPM | 110.0 | 1.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

| Part | Connects to | Note |
| --- | --- | --- |
| Encoder A channel | D2 (interrupt) | Counts every rising edge |
| Encoder B channel | D3 | Not used for speed alone; wire it for direction later |
| Encoder VCC and GND | 5V and GND | Check your encoder’s voltage |
| L298N ENA / IN1 / IN2 | D5 / D7 / D8 | Motor |
| Battery | L298N 12V input | Join 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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| RPM reads zero | Encoder not powered or wired to the wrong pin | Check D2 and the encoder supply |
| Speed oscillates | Gains too high | Lower Kp and Ki |
| Never reaches target | Target above what the supply can deliver, or integral limited | Check the open-loop maximum |
| Noisy RPM | Coarse counts at low speed | Lengthen the window or use period measurement |
| Motor runs backwards | Motor wires reversed | Swap 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](https://roboticsengineering.in/robotics-project-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.
