ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 78

Project: Closed-Loop Motor Speed Control

Measure, compare, correct.

Count encoder pulses over a fixed time to measure speed. The error is the target speed minus the measured speed. A proportional controller sets the PWM duty to error multiplied by a gain.

Adding an integral term removes leftover error, and a derivative term reduces overshoot. Tune one gain at a time, starting small, and clamp the output to the valid range.

This PID idea is behind heaters, drones and cruise control.

EXAMPLE
int16_t integral = 0;
int16_t pi_step(int16_t target, int16_t measured) {
    int16_t err = target - measured;
    integral += err;
    if (integral > 1000)  integral = 1000;
    if (integral < -1000) integral = -1000;
    int16_t out = err * 2 + integral / 8;   /* Kp=2, Ki=1/8 */
    if (out < 0) out = 0;
    if (out > 255) out = 255;
    return out;
}