- Asked 3/19
- 2070 Magh · 4 marks
- 2073 Bhadra · 4 marks
- 2074 Bhadra · 5 marks
Algorithm/pseudo-code for software PID
Short answer
The PID algorithm samples error at fixed period T, computes proportional, integral, and derivative terms discretely: P=Kp·e, I=I+Ki·T·e (clamped for anti-windup), D=Kd·(e-prev_e)/T. Output u=P+I+D is clamped to actuator limits and written to DAC/PWM. T must be much smaller than plant time constant for stability.
Write an algorithm (pseudo-code) to implement the PID controller in software.
A software PID samples the output at a fixed period T, computes the error, and updates the integral and derivative terms in discrete form. The routine is called from a timer interrupt every T seconds.
Discrete equations
e[k] = r - y[k]
I[k] = I[k-1] + Ki·T·e[k]
D[k] = Kd·(e[k] - e[k-1]) / T
u[k] = Kp·e[k] + I[k] + D[k]
Algorithm
- Initialise Kp, Ki, Kd, sampling period T, I = 0, prev_error = 0, output limits u_min, u_max.
- Wait for the timer tick (every T).
- Read the sensor (ADC) and get y.
- Compute error e = r - y.
- Compute P = Kp·e.
- Update I = I + Ki·T·e; clamp I between limits (anti-wind-up).
- Compute D = Kd·(e - prev_error)/T.
- Compute u = P + I + D; clamp u to [u_min, u_max].
- Write u to the actuator (DAC / PWM).
- Save prev_error = e and go to step 2.
Pseudo-code
init: I = 0; prev_e = 0
every T seconds (timer ISR):
y = ReadSensor()
e = r - y
P = Kp * e
I = I + Ki * T * e
if I > Imax then I = Imax
if I < Imin then I = Imin
D = Kd * (e - prev_e) / T
u = P + I + D
if u > Umax then u = Umax
if u < Umin then u = Umin
WriteActuator(u)
prev_e = e
The choice of T matters: it should be much shorter than the plant's time constant; otherwise control is poor and the loop may become unstable.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- PID controller types and applications · Embedded System, chapter 7
- GCD processor algorithm and VHDL · Embedded System, chapter 9 · asked 3×
- LCM processor algorithm and VHDL · Embedded System, chapter 9 · asked 2×
- VHDL architectures; elevator controller · Embedded System, chapter 9
- Algorithm versus pseudo-code · Computer Programming, chapter 2
- Gauss-Jordan pseudo-code · Numerical Method, chapter 3 · asked 4×
- Bisection method pseudo-code · Numerical Method, chapter 2 · asked 3×
- Power method pseudo-code · Numerical Method, chapter 3 · asked 2×