Projects / Closed-loop DC motor position

Closed-loop DC motor position

Intermediate4 hGuided buildReviewed

Build it step by step

0 of 7 done
  1. NANO

    Test the encoder

    Turn by hand, watch the count.

  2. NANO

    Find counts per turn

    One revolution.

  3. NANO

    Drive the motor

    Both directions.

  4. NANO

    Add P only

    Move to 90 degrees.

  5. NANO

    Add D

    Reduce overshoot.

  6. NANO

    Add a little I

    Remove the last error.

  7. NANO

    Plot steps

    90, 0, 180, 0.

In short

How do you build a closed-loop DC motor position?

A DC motor with an encoder moves to exact angles using PID. You need Arduino Nano, JGA25-370 encoder gear motor, L298N Dual H-Bridge Module and 12 V 2 A DC adapter. It takes 7 steps and about 240 minutes.

Level
Intermediate
Time
About 240 min
Parts
4

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Encoder VCCNano 5VEncoder power (check your motor's rating)
Encoder GNDNano GNDGround
Encoder ANano D2Interrupt 0
Encoder BNano D3Interrupt 1
L298N ENANano D5PWM speed (remove the ENA jumper)
L298N IN1 and IN2Nano D7 and D8Direction
L298N OUT1 and OUT2Motor wiresMotor drive
L298N 12V and GND12 V adapter plus and minusMotor supply
L298N GNDNano GNDCommon ground

Code

A motor you simply switch on has no idea where it is; add an encoder that counts every bit of turn and a controller that compares where it is with where you want it, and it can stop at an exact angle. PID is three ideas added together: push in proportion to the error (P), keep pushing if the error stays for a while (I), and ease off when it is closing fast (D). Tune in that order: raise P until it reacts quickly and starts to overshoot, add D to calm the overshoot, and use a little I only if it stops short. The counts-per-turn number depends on your motor, so find it by turning the shaft one revolution by hand and printing the count. The L298N loses about 2 V and gets warm, and a stalled motor draws a lot, so do not hold the shaft for long. Keep fingers and hair away from the gears. Arduino IDE, board "Arduino Nano" (try the Old Bootloader option if the upload fails).

Runs on a virtual Arduino Nano in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

// Closed-loop position control of an encoder motor with PID. Serial commands: t 90 (target degrees), p 2.0 / i 0.0 / d 0.1 (gains).
// Open the Serial Plotter at 115200 to see target and position. Board: Arduino Nano.
const byte ENCA = 2, ENCB = 3, ENA = 5, IN1 = 7, IN2 = 8;
const float COUNTS_PER_REV = 1320.0;   // check your motor: pulses per motor turn x 4 x gear ratio. Change this number.
volatile long count = 0;
float target = 0, kp = 2.0, ki = 0.0, kd = 0.1;
float integral = 0, lastErr = 0;
unsigned long lastRun = 0;
void isrA() { if (digitalRead(ENCA) == digitalRead(ENCB)) count--; else count++; }
void isrB() { if (digitalRead(ENCA) != digitalRead(ENCB)) count--; else count++; }
void drive(int pwm) {
  pwm = constrain(pwm, -255, 255);
  digitalWrite(IN1, pwm > 0); digitalWrite(IN2, pwm < 0);
  analogWrite(ENA, abs(pwm));
}
void setup() {
  Serial.begin(115200);
  pinMode(ENCA, INPUT_PULLUP); pinMode(ENCB, INPUT_PULLUP);
  pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(ENCA), isrA, CHANGE);
  attachInterrupt(digitalPinToInterrupt(ENCB), isrB, CHANGE);
}
void loop() {
  if (Serial.available()) {
    char c = Serial.read(); float v = Serial.parseFloat();
    if (c == 't') { target = v; integral = 0; }
    if (c == 'p') kp = v;
    if (c == 'i') ki = v;
    if (c == 'd') kd = v;
  }
  if (millis() - lastRun >= 10) {                      // 100 loops per second
    float dt = (millis() - lastRun) / 1000.0; lastRun = millis();
    noInterrupts(); long c = count; interrupts();
    float pos = c * 360.0 / COUNTS_PER_REV;
    float err = target - pos;
    integral = constrain(integral + err * dt, -100, 100);   // limit wind-up
    float deriv = (err - lastErr) / dt; lastErr = err;
    float out = kp * err + ki * integral + kd * deriv;
    if (fabs(err) < 0.5) out = 0;                        // dead band so it rests
    else out += (out > 0 ? 40 : -40);                    // push past the motor's stiction
    drive((int)out);
    Serial.print(target); Serial.print(' '); Serial.println(pos);
  }
}

What the serial monitor should show

Open the serial monitor at the baud rate in the code. This is what our simulator prints for a virtual Arduino Nano with its sensors at their default values. Your numbers will follow your real readings, but the format should match.

0.00 0.00

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
CountRises one way and falls the other
Target 90Shaft rests at 90 within 1 degree
Push the shaft awayIt returns
Step 0 to 180Smooth rise with small overshoot

If it does not work

Count goes the wrong way

Swap the A and B wires.

Motor runs away

Swap OUT1 and OUT2 or invert the sign.

Hunts around the target

Lower P or add the dead band.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the closed-loop DC motor position?

Arduino Nano, JGA25-370 encoder gear motor, L298N Dual H-Bridge Module and 12 V 2 A DC adapter.

How long does the closed-loop DC motor position take to build?

About 240 minutes for a intermediate maker, in 7 steps.

How do I know the closed-loop DC motor position works?

Count: Rises one way and falls the other. Target 90: Shaft rests at 90 within 1 degree. Push the shaft away: It returns.

Count goes the wrong way: what should I check?

Swap the A and B wires.

Motor runs away: what should I check?

Swap OUT1 and OUT2 or invert the sign.

Hunts around the target: what should I check?

Lower P or add the dead band.