PI controller with anti-windup
Implement an integer PI control step with clamped integral and output. A hard embedded C problem (Fixed-point and signal processing), run and graded in the…
hard · Fixed-point and signal processing · control · pid
A PI controller drives its output from the current error and from the accumulated error. Implement one control step:
- Add
errortointegral, then clampintegralto the range-i_limitto+i_limit. - Compute
(kp * error + ki * integral) / 256, with the division truncating toward zero. - Clamp that to
out_min..out_maxand return it.
The gains are fixed-point values scaled by 256, so kp = 512 means 2.0.
Starter code
int32_t pi_update(pi_t *c, int32_t error) {
// integrate, clamp the integral, combine, clamp the output
return 0;
}Example tests
Proportional term only
pi_t c = { 512, 0, 0, 1000, -100, 100 };
printf("%d ", pi_update(&c, 10));
printf("%d\n", pi_update(&c, -30));Expected output:
20 -60Integral term accumulates
pi_t c = { 0, 128, 0, 1000, -100, 100 };
for (int i = 0; i < 3; i++) printf("%d ", pi_update(&c, 10));
printf("\n");Expected output:
5 10 15Learn it first
- Fixed-point and signal processing · Scaling, rounding, saturation and filters without floating point.
More Fixed-point and signal processing problems
- Saturating addition · Add two 16-bit samples and clamp instead of wrapping.
- Q15 multiplication · Multiply two fractional fixed-point numbers.
- ADC counts to millivolts · Convert a 12-bit ADC reading to a voltage with correct rounding.
- Thermostat with hysteresis · Decide a heater state with two thresholds so it does not chatter.
- Moving average filter · Maintain the average of the last four samples in constant time.
- Exponential moving average · Implement a one-pole low-pass filter with a shift instead of a multiply.
- Linear interpolation · Interpolate between two calibration points without overflow.
- Temperature conversion with rounding · Convert tenths of a degree Celsius to Fahrenheit and round correctly below zero.
- Integer square root · Compute the square root of a 32-bit value without floating point.
- Fix: the battery always shows 0 % · Dividing before multiplying throws the whole result away in integer arithmetic.
- Fix: long measurements come out tiny · A tick count is scaled to microseconds through a product that overflows 32 bits.
- Hearing aid: amplify without wrapping · Apply a fixed-point gain to an audio sample, rounding and saturating instead of wrapping round.