HeapCrash / Challenges / Fixed-point speed loop

Fixed-point speed loop

A motor speed loop runs a fixed-point PI controller every 1 ms with Q16 gains. It behaves at low speed. During a fast reversal the motor briefly drives full power the wrong way, and after a long stall it overshoots wildly when released.

The code

Embedded C for Cortex-M. It compiles. There are 3 real bugs in it: the kind that pass a bench test and fail in the field.

#define KP_Q16  ((int32_t)(4.5 * 65536))
#define KI_Q16  ((int32_t)(0.8 * 65536))

static int32_t integ;

int16_t pi_step(int16_t target_rpm, int16_t rpm)
{
    int32_t err = target_rpm - rpm;
    integ += err;
    int32_t out = (KP_Q16 * err + KI_Q16 * integ) >> 16;
    return (int16_t)out;
}

What an interviewer expects

The bugs, reference fixes and the follow-up question are in the practice app, after you've tried it.

Companies that test this

Matched on the skills each company's embedded roles emphasise.

Related challenges

Flag the lines, say what breaks, then fix it and build it with clang in your browser.

Find the bugs