Home / Learn Chip Programming / Project 6: PID Motor Speed Controller
Project 6: PID Motor Speed Controller
Close the loop: measure speed with an encoder and control it with PWM and a PID algorithm.
Theory in plain words
What it is
The target RPM is set by you. An encoder counts pulses, a timer converts them to RPM, a PID controller computes the PWM duty and the motor driver applies it.
Why we use it
Feedback control keeps speed constant when the load changes. PID is used in drones, 3D printers, cars and factories.
How it works
Every 10 ms: error = setpoint - measured; P = Kp x error; I accumulates error with anti-windup; D reacts to change. Sum is limited to 0 to 100 percent PWM.
Where it is used
- Robots and drones
- CNC and 3D printers
- Temperature and pressure control
Equipment
The logic analyzer lets you see PWM and encoder pulses. The common ground between motor supply and board is essential.
Wiring
| From | To | Note |
|---|---|---|
| Nucleo PA8 (TIM1_CH1) | driver ENA / PWM input | PWM 20 kHz |
| Nucleo PB0, PB1 | driver IN1, IN2 | direction |
| Encoder A, B | Nucleo PA0, PA1 (TIM2 encoder mode) | hardware counts pulses |
| Motor supply 12 V | driver motor power | add 100 uF capacitor close to the driver |
| Battery GND | Nucleo GND | common ground |
Live PID tuner
Start with Ki = 0 and Kd = 0, raise Kp until it reacts quickly, then add Ki to remove the remaining error, then a little Kd to calm overshoot.
Code
typedef struct { float kp, ki, kd, integ, prev, out_min, out_max; } PID;
float pid_update(PID *p, float sp, float meas, float dt) {
float err = sp - meas;
p->integ += err * p->ki * dt;
if (p->integ > p->out_max) p->integ = p->out_max; // anti-windup clamp
if (p->integ < p->out_min) p->integ = p->out_min;
float d = (err - p->prev) / dt; p->prev = err;
float u = p->kp * err + p->integ + p->kd * d;
if (u > p->out_max) u = p->out_max; if (u < p->out_min) u = p->out_min;
return u;
}
// 100 Hz timer interrupt:
void TIM3_IRQHandler(void) {
static int32_t last; int32_t now = (int16_t)TIM2->CNT; int32_t delta = now - last; last = now;
float rpm = delta * 100.0f * 60.0f / PULSES_PER_REV; // pulses in 10 ms to rpm
float duty = pid_update(&pid, target_rpm, rpm, 0.01f);
TIM1->CCR1 = (uint32_t)(duty * (TIM1->ARR + 1) / 100.0f);
TIM3->SR = 0;
}- Test the driver without the PID: set a fixed duty and measure the motor voltage.
- Read the encoder count: rotate by hand and watch the counter.
- Compute RPM and print it. Compare with the expected rpm for the duty.
- Add P only. Then add I. Then D. Record each step with the serial plotter.
- Add a load (squeeze the shaft gently) and see how the controller reacts.
Quick quiz
1. What does the I term remove?
It accumulates error until it is zero.
2. Anti-windup is needed because...
Clamp it to avoid big overshoot.