PID Control With servo

Identify the control loop and drive operating mode first
In a servo system, PID control generates a correction from the error between a target and a measured value. Controlling a servo motor, however, does not always mean entering three external gains and sending a number to the motor. First identify whether you need to regulate position, velocity, torque or another quantity measured at the load.
Editor's note: Not every industrial servo loop uses a full PID controller. Some architectures use P control for position and PI control for velocity; others offer different controllers and feedforward options. If the drive already closes the position loop, adding another external loop with the same responsibility can cause interaction and instability. Establish where each loop is closed first.
Nested position, velocity and current loops
In a common cascaded architecture, position control compares commanded and actual position to generate a velocity reference. The velocity loop converts velocity error into a torque or current reference. The innermost current loop regulates motor currents. Consequently, position loop gain and current loop gain are different settings. Inner loops must respond fast enough to follow the demands of the outer loop.
Feedforward uses velocity and acceleration information from the motion profile to contribute to the command before a tracking error develops. It supports rather than replaces feedback. Whether a loop runs in the drive or in a motion controller depends on the selected architecture.
What do P, I and D change?
P, proportional action: Responds to the present error. A simple description is e = target − measurement and P = Kp × e. Insufficient gain can produce a weak response; excessive gain can excite mechanical resonance and oscillation.
I, integral action: Accumulates error over time and helps remove steady-state error. A discrete implementation can use I = previous I + Ki × e × dt. Continuing to accumulate while the command is saturated can cause integral windup.
D, derivative action: Responds to the rate of change and can provide damping when appropriately designed. Because it can amplify measurement noise, a derivative filter is commonly needed. In the example below, the derivative is calculated from the measurement with a negative sign, avoiding derivative kick caused by an abrupt target change. Review PID components together with PID gain adjustment.
What command does the drive receive?
Position mode: The controller supplies a target position or motion profile. With pulse and direction commands, pulse count determines the commanded position increment according to the electronic gearing, while pulse frequency determines the commanded rate of motion. Direction uses a separate signal. A numeric PID output is not automatically a pulse train. In an EtherCAT servo system, the selected operating mode determines command meaning and loop placement; the network name alone does not.
Velocity mode: An external position controller can produce a scaled, limited velocity command. Torque mode: An external controller supplies a torque or current-related reference, while the higher-level system must manage velocity and position behavior. Understand velocity versus position control and servo torque control before selecting the mode. Available analog and digital interfaces depend on the drive model.
A practical leadscrew example
A leadscrew with a 5 mm/revolution lead, directly coupled to the motor, ideally requires 20 motor revolutions for a 100 mm move. This is a load and transmission calculation, not PID tuning. The motion profile defines the velocity and acceleration used to cover that distance. The position loop then makes actual motion follow the reference.
If the target at one control instant is 100 mm and the measurement is 98.5 mm, the error is 1.5 mm. An outer loop whose output is velocity generates a velocity correction from that error. Gain units must match this relationship. Accurate motor encoder feedback does not automatically measure coupling slip or screw backlash; accuracy at the load needs separate consideration.
A practical order for commissioning and tuning
Start with mechanics and scaling: Check couplings, backlash, friction, load inertia, encoder direction and electronic gearing. Raising gains cannot compensate for incorrect motor and drive selection. Establish application-specific velocity, torque and travel limits, and use the manufacturer's identification and autotuning procedures.
Then evaluate the loops: Follow the manufacturer's method to verify inner loops, tune the velocity loop and then assess the position loop. During servo gain adjustment, change one parameter at a time and record following error, overshoot, settling time and motor current. Settings that work on one machine cannot be transferred blindly to another. A drive using integral time Ti may produce stronger integral action when that time is reduced, within the same parameter definition; do not confuse Ti with Ki.
Validate real operation: Test both directions, different loads and the actual motion profile. If high-frequency vibration appears, investigate resonance and measurement noise as well as controller gains. When troubleshooting PID control, compare trials under consistent conditions.
An educational Python example with an explicit time step
This code demonstrates one PID calculation step. dt is measured in seconds, and the output is normalized between −1 and +1. Gains are illustrative only. The example includes output limiting, conditional integration and a filtered derivative on measurement. Inputs must use consistent scaling.
from math import isfinite
class PID:
def __init__(self, kp, ki, kd, low, high, tau=0.02):
values = (kp, ki, kd, low, high, tau)
if not all(isfinite(x) for x in values):
raise ValueError("Parameters must be finite")
if min(kp, ki, kd, tau) < 0 or low >= high:
raise ValueError("Invalid gains or output limits")
self.kp, self.ki, self.kd = kp, ki, kd
self.low, self.high, self.tau = low, high, tau
self.reset()
def reset(self):
self.integral = 0.0
self.filtered_d = 0.0
self.previous_value = None
def update(self, setpoint, value, dt):
if not all(isfinite(x) for x in (setpoint, value, dt)) or dt <= 0:
raise ValueError("Finite inputs and dt > 0 required")
error = setpoint - value
raw_d = 0.0 if self.previous_value is None else -(value - self.previous_value) / dt
alpha = dt / (self.tau + dt)
self.filtered_d += alpha * (raw_d - self.filtered_d)
p = self.kp * error
d = self.kd * self.filtered_d
candidate_i = self.integral + self.ki * error * dt
trial = p + candidate_i + d
pushing_high = trial > self.high and error > 0
pushing_low = trial < self.low and error < 0
if pushing_high:
self.integral = max(self.integral, min(candidate_i, self.high - p - d))
elif pushing_low:
self.integral = min(self.integral, max(candidate_i, self.low - p - d))
else:
self.integral = candidate_i
self.previous_value = value
return max(self.low, min(self.high, p + self.integral + d))
pid = PID(kp=2.0, ki=0.5, kd=0.02, low=-1.0, high=1.0)
command = pid.update(setpoint=1.0, value=0.8, dt=0.01)
print(f"Normalized command: {command:.3f}")
The example prints 0.401. This number is not a voltage, current or pulse frequency; its physical meaning requires a defined interface and scaling. print() does not send a command to a drive. A real implementation must add feedback acquisition, scheduled execution, command conversion, communication-loss handling and fault management. Controller reset or tracking behavior during drive disable and mode changes must also be designed.
With PLC-based PID or a suitable motion controller, run the calculation in a scheduled task. For real-time control, an ordinary computer loop and a sleep call do not guarantee a specific cycle time. Sampling time and delays affect stability; using measured dt alone does not eliminate communication delay. A PID calculation does not replace machine emergency-stop or limit functions.
Related topics: PID questions and answers, servo velocity, torque and position control.