Closed-loop DC motor position
Build it step by step
0 of 7 doneTest the encoder
Turn by hand, watch the count.
Find counts per turn
One revolution.
Drive the motor
Both directions.
Add P only
Move to 90 degrees.
Add D
Reduce overshoot.
Add a little I
Remove the last error.
Plot steps
90, 0, 180, 0.
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
- Development BoardsBuyArduino Nano × 1
- Motors & Actuators
- Motor DriversBuy
- PowerBuy
Tick what you already own. It saves to My Garage, so “Build with what I have” knows.
Wiring
| From | To | Why |
|---|---|---|
| Encoder VCC | Nano 5V | Encoder power (check your motor's rating) |
| Encoder GND | Nano GND | Ground |
| Encoder A | Nano D2 | Interrupt 0 |
| Encoder B | Nano D3 | Interrupt 1 |
| L298N ENA | Nano D5 | PWM speed (remove the ENA jumper) |
| L298N IN1 and IN2 | Nano D7 and D8 | Direction |
| L298N OUT1 and OUT2 | Motor wires | Motor drive |
| L298N 12V and GND | 12 V adapter plus and minus | Motor supply |
| L298N GND | Nano GND | Common 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.
| Check | Expected |
|---|---|
| Count | Rises one way and falls the other |
| Target 90 | Shaft rests at 90 within 1 degree |
| Push the shaft away | It returns |
| Step 0 to 180 | Smooth 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 →
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.
