Software engineering
Rolling Your Own PID Controller From Error Terms to Motor Speed in C
A practical guide to implementing a discrete PID loop on embedded hardware, covering the three control terms, Ziegler-Nichols tuning, anti-windup strategies, and sample-time considerations, all illustrated with portable C code.

Why a PID controller matters for motion control
Motion control is one of the most common control problems in embedded engineering. Whether you are spinning a DC motor, positioning a servo, or regulating the speed of a fan, the goal is typically to make a system variable converge to a desired setpoint despite disturbances. A Proportional-Integral-Derivative (PID) controller is the workhorse for this task. It computes a control output by combining three terms derived from the error—the difference between the setpoint and the process variable.
In practice, PID controllers appear in everything from simple thermostats to high-performance servo drives. Their enduring popularity stems from a favorable trade-off: they require only a few scalar parameters (Kp, Ki, Kd) yet can achieve zero steady-state error, good disturbance rejection, and acceptable stability when properly tuned. On embedded hardware, implementing a PID loop from scratch gives you full visibility into the control logic, allows deterministic sample-rate scheduling, and avoids the overhead of opaque, vendor-specific libraries.
This article assumes you have a basic familiarity with C programming and embedded systems concepts such as timers and analog-to-digital conversion. We will proceed from the mathematical foundations to a portable code snippet that you can adapt to your own platform.
The three terms: proportional, integral, and derivative demystified
The PID algorithm operates on the error signal e(t) = setpoint - process_variable. Each term contributes a corrective action based on different aspects of this error.
- Proportional (P): The output is proportional to the current error. A high Kp reduces rise time but can cause overshoot or steady-state error if too low. The P-term alone will never drive the error to zero for a constant setpoint when there is load disturbance.
- Integral (I): The output is proportional to the integral of the error over time. The I-term accumulates past error, eliminating steady-state offset. However, aggressive integral action introduces phase lag and can lead to overshoot or oscillation. The integral gain Ki determines how aggressively the accumulated error influences the output.
- Derivative (D): The output is proportional to the rate of change of the error. The D-term predicts future error based on its current slope, adding damping to the system. It improves stability and reduces overshoot, but it is sensitive to measurement noise; a noisy error signal can cause the control output to chatter violently.
In discrete time, the ideal continuous-time integrals and derivatives are approximated. The choice of approximation affects numerical stability and tuning behavior, which we will explore in the next section.
Tuning your first loop with the Ziegler-Nichols method
Before writing code, the PID gains must be set. Several tuning methods exist, but the Ziegler-Nichols closed-loop method is a practical starting point for many motion-control systems.
1. Set Ki = 0 and Kd = 0. 2. Increase Kp until the output exhibits sustained, constant-amplitude oscillations around the setpoint. This critical gain is denoted Kuc. 3. Record the oscillation period Puc. 4. Apply the Ziegler-Nichols tabulated ratios to compute initial gains: - Kp = 0.6 × Kuc - Ki = 2 × Kp / Puc - Kd = Kp × Puc / 8
These formulas yield a moderately aggressive response. If the system oscillates excessively, reduce all gains by roughly 20 % and retest. If the response is too sluggish, increase gains cautiously. Note that Ziegler-Nichols provides a starting point; fine-tuning will likely be required to account for your specific plant dynamics, sampling rate, and actuator limits.
Handling anti-windup and rate limiting in firmware
A well-known problem in integral control is windup. When the control output saturates—such as a PWM duty cycle hitting 0 % or 100 %—the error continues to accumulate in the integral term. Upon saturation removal, the accumulated integral causes the output to overshoot dramatically, often leading to instability or prolonged settling time.
Anti-windup strategies address this by limiting the integral term’s growth. The most common firmware approach is *back-calculation*: when the output saturates, the integral term is decremented by a fraction of the saturation error, effectively pulling the accumulated state back toward the unsaturated region. A simple implementation checks whether the computed output exceeds the actuator limits; if so, the integral accumulator is adjusted rather than freely integrated.
Rate limiting on the output is another useful safeguard, especially when driving low-inertia loads or when the control algorithm runs at a high frequency. By constraining the change in output per sample period (e.g., Δu ≤ Δu_max), you prevent abrupt command changes that could excite mechanical resonances or stress drive electronics. Both anti-windup and rate limiting are orthogonal to the P/I/D terms and should be implemented as post-processing steps after the raw PID sum is computed.
Discrete vs. continuous implementation and sample time effects
The PID algorithm is originally formulated in continuous time, but embedded processors operate in discrete time. The transition from continuous to discrete requires careful consideration of the sample period Ts.
- Euler approximation: The most straightforward discretization replaces the integral with a summation and the derivative with a finite difference. The update equation becomes u[k] = Kp·e[k] + Ki·Σe[i]·Ts + Kd·(e[k] - e[k-1])/Ts. This form is easy to implement but can introduce numerical error if Ts is too large or too small relative to the system dynamics.
- Sample time selection: The sample period must be fast enough to capture the fastest dynamics of the plant (including sensor bandwidth and actuator rise time) but not so fast that the processor load becomes prohibitive. A typical rule of thumb is to choose Ts ≤ 1/10 of the dominant system time constant. For motor speed control, sample rates in the 1–10 kHz range are common, depending on the motor size and control bandwidth.
- Time-step independence: Some implementations scale the integral and derivative terms by Ts explicitly, while others absorb Ts into the gain definitions (Ki_discrete = Ki_continuous × Ts). Whichever convention you adopt, document it clearly and maintain consistency; changing the sample rate without re-tuning will degrade performance.
Practical C code snippet with comments
The following ISO C99-compatible snippet implements a discrete PID controller with anti-windup and rate limiting. It is deliberately platform-agnostic; you will need to provide the error measurement, setpoint, and actuator limits from your own hardware abstraction layer.
/* PID controller for motor speed control
* Compiles with any C99 compiler.
* Assumes periodic invocation from a timer ISR at period Ts.
*/
typedef struct {
float Kp; /**< Proportional gain */
float Ki; /**< Integral gain (already scaled by Ts) */
float Kd; /**< Derivative gain (already scaled by Ts) */
float out_min; /**< Minimum actuator output (e.g., 0.0) */
float out_max; /**< Maximum actuator output (e.g., 1.0) */
float out_rate_max; /**< Maximum change per sample (e.g., 0.1) */
float integral; /**< Internal integral accumulator */
float prev_error; /**< Previous error for derivative term */
float last_output; /**< Previous output for rate limiting */
} pid_controller_t;
void pid_init(pid_controller_t *c, float Kp, float Ki, float Kd,
float out_min, float out_max, float out_rate_max)
{
c->Kp = Kp;
c->Ki = Ki;
c->Kd = Kd;
c->out_min = out_min;
c->out_max = out_max;
c->out_rate_max = out_rate_max;
c->integral = 0.0f;
c->prev_error = 0.0f;
c->last_output = (out_min + out_max) / 2.0f;
}
/* Compute the control output for the current error sample.
* Returns the saturated, rate-limited output.
*/
float pid_compute(pid_controller_t *c, float setpoint, float process_variable, float Ts)
{
float error = setpoint - process_variable;
/* --- Proportional term --- */
float p_term = c->Kp * error;
/* --- Integral term with back-calculation anti-windup --- */
/* Accumulate error; if output would saturate, pull integral back */
c->integral += c->Ki * error * Ts;
float raw_output = c->last_output + p_term + c->integral + c->Kd * (error - c->prev_error) / Ts;
/* Anti-windup: if raw output saturated, adjust integral to reduce saturation */
if (raw_output > c->out_max) {
c->integral -= (raw_output - c->out_max);
raw_output = c->out_max;
} else if (raw_output < c->out_min) {
c->integral += (c->out_min - raw_output);
raw_output = c->out_min;
}
/* --- Rate limiting --- */
/* Constrain how much the output can change from the previous sample */
float output_delta = raw_output - c->last_output;
if (output_delta > c->out_rate_max) {
raw_output = c->last_output + c->out_rate_max;
} else if (output_delta < -c->out_rate_max) {
raw_output = c->last_output - c->out_rate_max;
}
/* Store state for next invocation */
c->prev_error = error;
c->last_output = raw_output;
return raw_output;
}Note on gain scaling: In this snippet, Ki and Kd are expected to be given in continuous‑time units (e.g., Ki in 1/s). The multiplication by Ts inside the integral term and the division by Ts in the derivative term make the gains sample‑rate dependent. If you change the sampling frequency, you must re‑scale Ki and Kd proportionally, or re‑tune the loop using the new Ts.
Checklist: verifying your PID implementation on hardware
Before deploying a PID loop to a production system, validate the following items on the target hardware:
- [ ] Sample‑rate stability: Confirm that the control loop executes at the intended period Ts. Use a scope or logic analyzer to verify jitter is within acceptable bounds; excessive jitter degrades derivative action.
- [ ] Setpoint step response: Apply a sudden setpoint change and record the process variable. Check for overshoot, settling time, and steady‑state error. Adjust Kp, Ki, Kd iteratively.
- [ ] Disturbance rejection: Introduce a known load disturbance (e.g., a sudden torque load on a motor) and observe the recovery time. The integral term should eliminate offset, but excessive Ki may cause oscillation.
- [ ] Saturation and anti-windup: Drive the actuator to its physical limits (e.g., 0 % or 100 % duty cycle). Verify that the integral term does not wind up; the output should return smoothly to the setpoint once the load is removed.
- [ ] Noise robustness: Add intentional measurement noise or observe real sensor noise. Monitor the control output for chatter; if the derivative term amplifies noise excessively, consider filtering the error or reducing Kd.
- [ ] Rate‑limit behavior: Observe the output change per sample. It should respect the out_rate_max constraint without causing limit‑cycle oscillation.
- [ ] Numerical precision: If your system uses 16‑bit fixed‑point arithmetic, verify that the accumulated integral and intermediate sums do not overflow. Consider scaling gains or using a wider intermediate type.
- [ ] Documentation: Record the final gain values, the sample period, and the anti-windup/rate‑limit parameters used. This aids future re‑tuning or platform migration.
Remember that this article does not replace a site-specific safety assessment. For safety‑critical machinery, always perform a complete risk analysis and validate the control system under worst‑case operating conditions.
---
*Keywords: PID, embedded control, motor speed, C programming, anti-windup, discrete control, Ziegler-Nichols*
Explore Rootcastle engineering tools → · Public profiles and publications
Try the method in the LABEngineering sandbox →

