Motor speed PID (encoder and flywheel)
Hold a 12 V motor at a set speed: count its encoder on interrupts, add a feedforward, close a PI loop, and tune it live while a load pulls on the shaft.
Control · Advanced
In a real product: Conveyor belt drive (Industrial): The belt holds its speed as parcels land on it.
A motor's speed falls the moment a load lands on its shaft, and rises when the supply does. A speed loop measures the speed, compares it with the setpoint and corrects the drive, many times a second. Here the motor is a simulated plant with real physics: a 12 V brushed motor turning a steel flywheel, with a Hall encoder on its back. Open the World tool to watch the response, the step metrics and the load.
What you'll learn
- Counting a quadrature encoder on two interrupts: four counts a cycle, and the direction from A against B
- Measuring speed over a fixed period, and filtering the measurement so its quantization does not shake the loop
- A feedforward that does most of the work, and a PI loop that does the rest
- Integral windup on a large step, and holding the integral until the speed is close
- Rejecting a disturbance: a load on the shaft
How it works
The motor runs through a TB6612FNG from a 12 V supply. With the driver's PWM input pulsed, the motor sees 12 V for part of each period and a short brake for the rest, so its average voltage is the duty times 12 V. At 12 V it turns at about 3000 rpm with no load, and its flywheel gives it a time constant of about 150 ms.
The encoder has 12 cycles a turn on A and B. An interrupt on each edge of both adds or takes one from the count, depending on whether A and B are equal: 48 counts a turn. Every 20 ms the sketch turns the counts into rpm and filters it (rpm = 0.6·rpm + 0.4·new), since one count in 20 ms is already 62.5 rpm.
The control output is setpoint / 11.8 + Kp·error + Ki·integral. The first term is the feedforward: the duty that gives that speed with no load (3000 rpm at 255). The PI terms correct what it gets wrong, a load or a weak supply. The integral starts only once the speed is within 10% of the setpoint, and stops while the output is pinned at 0 or 255: without that, the large error during the rise winds it up, and the motor overshoots by half.
The sketch prints setpoint:, rpm: and duty: ten times a second, which the Serial Plotter draws and the World tool measures against. It reads s<rpm> for a new setpoint and kp=, ki=, kd= for new gains: the World tool's gain sliders send those lines.
Try this
- Open the World tool, run, and read the rise, overshoot and settling time. Send
s2500, thens800. - Add 40 mN·m of load from the World tool: the speed dips, then the integral brings it back. Set
ki=0and try again. - Remove the
reachedcheck and sends1500from a standstill: watch the overshoot the wound-up integral causes. - Push Kp up with the slider until the status says oscillating. The measurement's filter and the 20 ms period are the delay that makes it ring.
- Take out the feedforward and tune the PI loop to do it alone.
sketch.ino
// Motor speed PID: a 12 V motor with a flywheel through a TB6612FNG (AIN1 7, AIN2 8, PWMA 5, STBY 9), its encoder's
// A on 2 and B on 3. Serial: s<rpm> sets the speed; kp=, ki=, kd= set the gains.
const int AIN1 = 7, AIN2 = 8, PWMA = 5, STBY = 9, ENC_A = 2, ENC_B = 3;
const float COUNTS_PER_REV = 48.0; // 12 cycles a turn, both edges of A and B
const float RPM_PER_DUTY = 3000.0 / 255;
const unsigned long PERIOD_MS = 20;
volatile long count = 0;
float setpoint = 1500, kp = 0.03, ki = 0.6, kd = 0;
float rpm = 0, integral = 0, lastError = 0;
bool reached = false; // the speed has come within 10% of the setpoint since it changed
int duty = 0;
long lastCount = 0;
unsigned long lastRun = 0, lastPrint = 0;
String line;
void edgeA() { count += digitalRead(ENC_A) == digitalRead(ENC_B) ? -1 : 1; }
void edgeB() { count += digitalRead(ENC_A) == digitalRead(ENC_B) ? 1 : -1; }
void command(const String &c) {
if (c.startsWith("kp=")) kp = c.substring(3).toFloat();
else if (c.startsWith("ki=")) ki = c.substring(3).toFloat();
else if (c.startsWith("kd=")) kd = c.substring(3).toFloat();
else if (c.startsWith("s")) { setpoint = c.substring(1).toFloat(); reached = false; integral = 0; }
}
void setup() {
Serial.begin(115200);
pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT); pinMode(PWMA, OUTPUT); pinMode(STBY, OUTPUT);
digitalWrite(STBY, HIGH);
digitalWrite(AIN1, HIGH); // forward
digitalWrite(AIN2, LOW);
attachInterrupt(digitalPinToInterrupt(ENC_A), edgeA, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENC_B), edgeB, CHANGE);
}
void loop() {
while (Serial.available()) {
char ch = Serial.read();
if (ch == '\n') { command(line); line = ""; } else if (ch != '\r') line += ch;
}
unsigned long now = millis();
if (now - lastRun >= PERIOD_MS) {
float dt = (now - lastRun) / 1000.0;
lastRun = now;
noInterrupts();
long c = count;
interrupts();
rpm = 0.6 * rpm + 0.4 * ((c - lastCount) / COUNTS_PER_REV / dt * 60.0);
lastCount = c;
float error = setpoint - rpm;
float u = setpoint / RPM_PER_DUTY + kp * error + ki * integral + kd * (error - lastError) / dt;
if (fabs(error) < 0.1 * setpoint) reached = true;
if (reached && u > 0 && u < 255) integral += error * dt; // anti-windup
lastError = error;
duty = constrain((int)u, 0, 255);
analogWrite(PWMA, duty);
}
if (now - lastPrint >= 100) {
lastPrint = now;
Serial.print("setpoint:"); Serial.print(setpoint, 0);
Serial.print(" rpm:"); Serial.print(rpm, 0);
Serial.print(" duty:"); Serial.println(duty);
}
}