PID Control
What is PID control?
PID control (proportional–integral–derivative control) is a feedback method that keeps a measured quantity, such as a temperature or a motor speed, at a target value. A PID controller compares the target (the setpoint) with the measurement, and sets its output from three terms: the error now, the error accumulated over time, and how fast the error is changing.

Setpoint, process variable and controller output for a PID loop on a simulated heating process with dead time. Try the interactive simulator.
- A PID controller sets its output from the error between setpoint and measurement: P reacts to the error now, I removes the error that remains, D damps the response.
- A step response shows how well a loop is tuned, through four numbers: rise time, overshoot, settling time and steady-state error.
- Tune by hand with P first, then I, then D, or start from a test such as Ziegler–Nichols or lambda tuning.
- Ziegler–Nichols gives fast, oscillatory loops; lambda tuning gives slower ones with no overshoot, and lets you choose the speed.
- Real controllers need anti-windup, a filtered derivative on the measurement, and a sample time well below the process's time constant.
How a feedback control loop works
A feedback loop has four signals. The setpoint (SP, or reference r) is the value you want, for example 60 °C. The process variable (PV, or y) is what a sensor measures. The error is the setpoint minus the process variable, . The controller output (CO, or u) is what the controller sends to the actuator: a heater's power, a valve position or a motor voltage, often as 0 to 100%.
The loop runs continuously. If a door opens and the oven cools, the error grows, the controller turns the heater up, the temperature recovers and the error shrinks again. A change that the controller didn't cause, like the open door, is a disturbance. A good loop follows setpoint changes quickly and rejects disturbances, without oscillating and without driving the actuator harder than it can go.
Control without feedback, where the output is set from a recipe and never checks the result, is open-loop control. It is simple, but it can't correct for disturbances or for a process that changes over time.
The P, I and D terms
In the parallel (independent-gain) form, the controller output is the sum of three terms:
, and are the proportional, integral and derivative gains. Industrial controllers more often use the standard (ISA) form, with one gain and two times:
The two are the same controller written differently: and . The integral time is in seconds (some controllers use repeats per minute, its inverse), and the derivative time is in seconds too. Check which form a controller uses before copying gains from one to another: a of 0.5 and a of 0.5 s are very different settings.
Proportional: the error now
The P term pushes in proportion to the error. A bigger reacts harder and faster, but with a process that has delay it also overshoots and, past a certain gain, oscillates. On its own, P control leaves a steady-state error (offset) whenever the process needs a non-zero output to stay at the setpoint, because with zero error the P term is zero. A loop with process gain and P-only gain settles with a remaining error of of the step: with and , a quarter of it.
Some controllers set the P action as a proportional band instead: the error, in % of the measurement range, that drives the output from 0 to 100%. A proportional band of 50% is a gain of 2.
Integral: the error that remains
The I term adds up the error over time, so it keeps growing as long as any error is left, until the output is exactly what holds the process at the setpoint. It removes the offset. Too much integral action makes the loop slow to settle, with long, lazy oscillations, and it causes integral windup when the output is limited (see practical problems).
Derivative: the trend
The D term reacts to how fast the error is changing, so it acts before the error gets large: as the process variable races towards the setpoint, D eases the output off, which reduces overshoot. It also amplifies measurement noise, because noise changes fast. Many loops, especially in process plants where measurements are noisy, run as PI with no D at all.
The discrete PID formula
A digital controller runs once every sample time , so the integral becomes a running sum and the derivative a difference:
In code, the sum is a variable that adds on each sample. Storing the integral term itself, rather than the sum of errors, means a change to doesn't make the output jump. The simulator below runs this formula every 10 ms, with the derivative taken from the measurement and passed through a 0.2 s low-pass filter.
What is a step response?
A step response is how a system's output moves after its input changes suddenly from one constant value to another. For a control loop, the step is usually a setpoint change, and the response is the process variable over the following seconds or minutes. It is the standard test for judging a loop's tuning, because the same handful of features appear on every step response and can be measured.
How to read a step response
| Metric | Definition | What it tells you | Usual fix if too large |
|---|---|---|---|
| Rise time | Time from 10% to 90% of the step | How fast the loop responds | More , or more |
| Overshoot | Peak beyond the final value, as % of the step | How aggressive or underdamped the loop is | Less or , or some |
| Settling time | Time after the step to enter, and stay inside, ±2% of the final value | When the response is finished | Depends: less oscillation, or more speed |
| Steady-state error | Setpoint minus the final value | Whether the loop reaches the target | Add or increase |
| Peak time | Time from the step to the highest point | Speed of an underdamped loop | As for rise time |
Some textbooks use 0 to 100% for the rise time of underdamped systems, or a ±5% settling band. Say which definition you use when you quote a number. The simulator measures against the new setpoint, which is the final value whenever the loop has integral action.
For a second-order system, overshoot depends only on the damping ratio ζ: %. A damping ratio of 0.7 gives about 4.6% overshoot, 0.5 gives 16%, and 0.3 gives 37%. Many loops are tuned for a few per cent to 20%, depending on whether overshoot harms the product; a chemical reactor or a robot arm near an obstacle may need none.
Rise time and overshoot pull against each other: a faster loop overshoots more. Settling time is often best at a moderate overshoot, because a very slow loop takes long to arrive and a very fast one takes long to stop ringing.
How to tune a PID controller
PID tuning means choosing , and so the loop meets its goals: fast enough, little enough overshoot, and robust to disturbances and to changes in the process. There are three families of methods: manual trial and error, rules applied to a measured test (Ziegler–Nichols, Cohen–Coon, lambda), and software that fits a model and optimises the gains.
Manual PID tuning procedure
- Put the loop in manual, check the actuator works in both directions, and check the controller's direction: if more output raises the process variable, the controller must be reverse acting (output rises when PV falls below SP).
- Set and to zero. Raise in steps, testing each with a small setpoint step, until the response is fast with a small overshoot. Expect an offset.
- Add integral action. Raise until the offset disappears in about the time the loop takes to settle. If the response starts to oscillate slowly, back off or reduce a little.
- Add derivative action only if the loop overshoots more than you want and the measurement is clean. Raise until the overshoot drops; stop if the output turns noisy.
- Test with a load disturbance as well as a setpoint step, because most loops spend their life rejecting disturbances. Record the final gains and the test results.
Change one gain at a time, and give each test long enough to settle. In the simulator, a 20% step on the default process takes 20 to 30 seconds of process time to finish.
The Ziegler–Nichols tuning method
The Ziegler–Nichols method is the best-known set of PID tuning rules, and one of the earliest (Callender, Hartree and Porter published rules in 1936). It comes from John Ziegler and Nathaniel Nichols of the Taylor Instrument Companies in 1942. Its closed-loop (ultimate gain) version needs one test:
- Set the controller to P only.
- Raise until the process variable oscillates with a constant amplitude, neither growing nor dying away. That gain is the ultimate gain .
- Measure the period of the oscillation, the ultimate period .
- Calculate the gains from the table.
| Controller | |||
|---|---|---|---|
| P | – | – | |
| PI | – | ||
| PID |
For the parallel form, and .
Worked example
The simulator's default process has a gain , a time constant s and a dead time s. For this first-order-plus-dead-time process, the loop oscillates at the frequency where the process lags by 180°, , which gives rad/s. So:
- s, and ;
- the PID rule gives , s and s, or in parallel form /s and s.
The simulator's Ziegler–Nichols button finds and by simulation instead, by halving the interval between a gain that decays and one that grows: it gets 6.91 and 7.34 s, within 0.3% of the calculation.
The rules were designed for a quarter-amplitude decay, each overshoot a quarter of the one before, which is fast but oscillatory. With the gains above and no output limit, a setpoint step overshoots by about 56%. With the simulator's 0 to 100% output limit, the 20% step overshoots by about 10%, because the limit clips the output. Treat Ziegler–Nichols gains as a starting point, and reduce if the overshoot is too large.
Driving a real plant to the edge of instability for the test is often unacceptable. The relay method of Åström and Hägglund gets the same two numbers safely: it swaps the controller for an on-off relay, which makes the loop oscillate with a small, controlled amplitude at the ultimate period. Many controllers with an autotune button use it.
Cohen–Coon and lambda tuning
Both start from an open-loop step test. With the controller in manual, step the output by a few per cent and record the process variable. Fit a first-order-plus-dead-time (FOPDT) model: the process gain (change in PV divided by change in output), the dead time (delay before the PV starts to move) and the time constant (time to 63% of the final change, after the dead time).
- Cohen–Coon (1953) rules turn , and into gains aimed, like Ziegler–Nichols, at quarter-amplitude decay. They handle processes with a long dead time relative to the time constant better than Ziegler–Nichols, but are just as aggressive.
- Lambda tuning (an internal model control, IMC, method) lets you choose the closed-loop time constant : how fast you want the loop to respond. For a PI controller on an FOPDT process, and . Skogestad's SIMC rules refine this with for slow processes, and suggest as a good default for a fast, robust loop.
For the default process, s gives and /s; in the simulator the 20% step then rises in 7.9 s with no overshoot and settles in about 16 s. Choosing s, a common conservative choice, gives , /s and a settling time of about 32 s.
PID tuning methods compared
PID tuning methods differ in the test they need and the response they aim for, from trial and error to model-based rules such as lambda tuning.
| Method | Test needed | Response it aims for | Best for | Watch out for |
|---|---|---|---|---|
| Manual (trial and error) | Repeated setpoint steps | Whatever you judge right | Fast loops (flow, motors) where tests take seconds | Slow on slow processes; depends on experience |
| Ziegler–Nichols closed loop | Sustained oscillation at | Quarter-amplitude decay | A quick first setting | Aggressive; driving a plant to oscillation can be unsafe |
| Relay autotune | Small relay oscillation | As the rules applied to it | Built-in autotune buttons | Disturbances during the test spoil it |
| Cohen–Coon | Open-loop step test | Quarter-amplitude decay | Processes with long dead time | Aggressive; needs a good FOPDT fit |
| Lambda (IMC, SIMC) | Open-loop step test | No overshoot, chosen speed | Process plants, interacting loops, valves you don't want to wear | Slow if is chosen too large |
| Model-based software | Step or frequency data | Optimised for chosen goals and margins | Critical or complex loops | Only as good as the model |
P vs PI vs PID
| Controller | Removes offset? | Typical use |
|---|---|---|
| P | No | Level control where an offset is acceptable, inner loops of a cascade |
| PI | Yes | Most loops: flow, pressure, level, temperature, motor speed |
| PD | No | Position control where the process already integrates, such as a motor's angle |
| PID | Yes | Slow, lag-dominated loops with clean measurements: temperature, multirotor attitude |
Practical PID problems and their fixes
Industrial controllers add the following features to the textbook formula, and the simulator has most of them.
Integral windup and anti-windup
Every actuator has limits: a valve can't open more than fully, and a heater can't give more than 100% power. When the output is saturated and the error persists, the integral keeps growing even though the output can't. When the process finally reaches the setpoint, the oversized integral holds the output at its limit, and the process overshoots well past the setpoint before the integral unwinds. That is integral windup.
Anti-windup prevents it. Clamping (conditional integration) stops integrating while the output is saturated and the error would push it further. Back-calculation feeds the difference between the requested and the actual output back into the integrator, bleeding it off. In the simulator, with the default gains and the output limit at 65%, a step from 40% to 60% overshoots by about 20% and takes about 44 s to settle with anti-windup off, against no overshoot and 20 s with it on.
Derivative kick and derivative filtering
If the D term acts on the error, a setpoint step makes the error jump, its derivative is momentarily huge, and the output spikes: a derivative kick. The fix is to take the derivative of the measurement instead of the error ( in place of ). The two are the same between setpoint changes, so disturbance rejection doesn't change.
The derivative of a noisy measurement is noisier still. Practical controllers low-pass filter the D term, with a filter time constant of where is typically between 2 and 20 (Åström and Murray). In the simulator, set the D acts on menu to error, step the setpoint, and watch the spike in the D trace.
Setpoint weighting
Weighting lets you tune for disturbances and setpoint changes separately. The P term acts on instead of , with between 0 and 1, while the I term keeps the full error so the loop still reaches the setpoint. With a setpoint step gives a smaller output jump and less overshoot, without making the loop slower to reject disturbances. Taking the derivative of the measurement only, as above, is the same idea with a derivative weight of 0.
Saturation and rate limits
Besides windup, saturation sets a speed limit: if the output sits at 100% during a large step, no tuning can make the response faster. Tune with step sizes like the ones the loop will see, since a loop tuned on small steps may behave differently on large ones. Some actuators also limit the rate of change, such as a valve with a slow motor; that adds lag the tuning has to allow for.
Sample time
A digital PID needs to sample several times faster than the fastest dynamics it controls. Too slow a sample time adds delay, about half a sample on average plus computation time, which erodes the stability margin. For a temperature loop with a time constant of minutes, one sample a second is plenty; motor current loops run at thousands of samples a second. Keep the sample time constant too, because a jittery makes the integral and derivative wrong.
Stability margins and the Bode plot
Step tests show how a loop behaves; frequency response shows how close it is to oscillating. Draw a Bode plot of the open-loop response (controller times process) and read the gain margin and phase margin: how much more gain, or how much more delay, the loop can take before it oscillates. Ziegler–Nichols tuning tends to leave small margins; lambda tuning with at least equal to the dead time leaves larger ones. Dead time is what limits most loops, because it adds phase lag that grows with frequency, radians, while adding nothing to the gain.
Where PID control is used
PID control runs most of the feedback loops in industry, from process plants to motor drives and temperature controllers.
- Process plants. Flow, pressure, level and temperature loops in refineries, chemical plants and paper mills. A Honeywell survey of more than 11,000 controllers in those industries found that 97% of regulatory controllers used a PID algorithm (reported by Desborough and Miller, 2002). Operators watch the loops on HMI and SCADA trend charts, and SciChart is used to build HMI and SCADA software.
- Temperature control. Ovens, furnaces, 3D-printer hot ends, incubators, and heating, ventilation and air conditioning. Thermal loops are slow and lag-dominated, so they often use derivative action.
- Motor speed and position. Drives, conveyors, CNC axes and robot joints, usually with a fast current loop inside a speed loop inside a position loop (a cascade).
- Drones and vehicles. Multirotor flight controllers stabilise attitude with cascaded PID loops on angle and angular rate, tuned from step responses logged in flight. Cruise control and lane keeping use PID too.
- Test and measurement. Environmental chambers, dynamometers and power supplies hold set conditions while an instrument records data; see SciChart in instrumentation software.
Common PID tuning mistakes
Many PID tuning problems come from testing the wrong thing or from mixing up controller forms, units and direction.
- Tuning only for setpoint steps. Most loops spend their time rejecting disturbances. Test with a load change too: a loop with no setpoint overshoot can still recover slowly from a disturbance.
- Copying gains between controllers. Parallel, standard and series forms use different numbers for the same behaviour, and some controllers use proportional band or repeats per minute. Convert before you copy.
- Wrong controller direction. A direct-acting controller on a process that needs reverse action drives the output to a limit and stays there. Check the sign before tuning.
- Running derivative on a noisy signal. The D term turns noise into actuator chatter and wear. Filter it, or use PI.
- Leaving out anti-windup. Any loop whose output can saturate, which is nearly all of them, needs it. Large steps or start-up from cold then overshoot badly.
- Tuning at one operating point only. Process gain and dead time often change with load, flow or temperature. Tune at the worst case, or schedule the gains.
- Fighting a mechanical problem with tuning. A sticking valve (stiction) or backlash makes a loop cycle whatever the gains. Check the actuator with a manual step first.
How to chart a PID control loop in JavaScript, React or Angular
Tuning a loop means watching several signals move together at once: setpoint, process variable, controller output and its three parts, sampled tens or hundreds of times a second. The demo simulates the process and the controller in the browser every 10 ms of process time, running four times faster than real time, and streams a point every 0.1 s into two scrolling trends: the setpoint and process variable, and the controller output with its P, I and D parts.
Change Kp, Ki and Kd to tune the controller, and Gain K, Time constant τ and Dead time θ to change the process. Step setpoint toggles the setpoint between 40% and 60%, and Add load disturbance takes 15% off the process input. Lower the Output limit and untick Anti-windup to see integral windup, and set D acts on to error to see derivative kick. Ziegler–Nichols finds the ultimate gain and period for the current process and applies the classic PID rule. The readout measures each step's rise time, overshoot and settling time as it happens. Hover for values; scrolling or dragging a chart pauses it so you can zoom and pan, and Pause stops or restarts the run.
Here is the code for this chart. The process, the PID controller, the Ziegler–Nichols search and the step metrics are plain JavaScript; SciChart.js draws the trends as line series with a FIFO buffer. The React and Angular versions chart a logged loop from your own data.
- JavaScript
- React
- Angular
// A real-time PID control loop simulator: setpoint, process variable and controller output, charted with SciChart.js
const {
SciChartSurface,
SciChartVerticalGroup,
NumericAxis,
NumberRange,
EAutoRange,
EAxisAlignment,
FastLineRenderableSeries,
XyDataSeries,
HorizontalLineAnnotation,
ELabelPlacement,
LegendModifier,
ELegendPlacement,
ELegendOrientation,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
EXyDirection
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
const DT = 0.01; // simulation step (s): the controller's sample time
const RECORD_EVERY = 10; // plot one point every 10 steps (0.1 s)
const WINDOW = 60; // seconds of process time on screen
const SPEED = 4; // process time runs 4 times faster than real time
const SETPOINTS = [40, 60]; // the setpoint step toggles between these (% of range)
const DISTURBANCE = -15; // load disturbance added to the process input (%)
const D_FILTER = 0.2; // time constant of the derivative filter (s)
// --- The process: first order plus dead time (FOPDT), like a heater or a motor ---
// τ·dy/dt = K·u(t − θ) − y, solved with Euler steps; a ring buffer holds the dead time
function createProcess(initialOutput) {
let buffer = new Float64Array(1);
let head = 0;
const process = {
gain: 1,
tau: 8,
theta: 2,
load: 0,
y: 0,
// Start in steady state with the input held at u
reset(u) {
buffer = new Float64Array(Math.max(1, Math.round(process.theta / DT))).fill(u);
head = 0;
process.y = process.gain * u;
},
// After a dead-time change, refill the buffer with the latest input (keeps it simple)
resizeDelay() {
const last = buffer[(head + buffer.length - 1) % buffer.length];
const size = Math.max(1, Math.round(process.theta / DT));
if (size === buffer.length) return;
buffer = new Float64Array(size).fill(last);
head = 0;
},
step(u) {
const delayed = buffer[head]; // the input from θ seconds ago
buffer[head] = u + process.load;
head = (head + 1) % buffer.length;
process.y += (DT / process.tau) * (process.gain * delayed - process.y);
return process.y;
}
};
process.reset(initialOutput);
return process;
}
// --- The PID controller: parallel form u = Kp·e + Ki·∫e dt + Kd·de/dt, one sample every DT ---
function createPid() {
let previous = null;
let derivative = 0;
const pid = {
kp: 2,
ki: 0.3,
kd: 1,
uMin: 0,
uMax: 100,
antiWindup: true,
dOnMeasurement: true,
integral: 0, // the I term itself, so changing Ki doesn't bump the output
update(setpoint, measurement) {
const error = setpoint - measurement;
// Derivative of the error, or of minus the measurement, which ignores setpoint steps (no derivative kick)
const signal = pid.dOnMeasurement ? -measurement : error;
const raw = previous === null ? 0 : (signal - previous) / DT;
previous = signal;
derivative += (DT / (D_FILTER + DT)) * (raw - derivative); // first-order low-pass filter on the derivative
const p = pid.kp * error;
const d = pid.kd * derivative;
const unclamped = p + pid.integral + d;
const u = Math.min(pid.uMax, Math.max(pid.uMin, unclamped)); // actuator limits
// Anti-windup by clamping: stop integrating while the output is saturated and the error pushes it further
const saturated = u !== unclamped && Math.sign(error) === Math.sign(unclamped - u);
if (!(pid.antiWindup && saturated)) pid.integral += pid.ki * error * DT;
return { u, p, i: pid.integral, d };
},
reset(integral) {
pid.integral = integral;
previous = null;
derivative = 0;
}
};
return pid;
}
// --- Ziegler–Nichols closed-loop method, done by simulation ---
// With P control only, raise Kp until the loop oscillates with a constant amplitude: that gain is the ultimate
// gain Ku and the oscillation period is Tu. Bisection: the loop is unstable above Ku, decaying below it.
function findUltimateGain(gain, tau, theta) {
const duration = 20 * (tau + theta);
const trial = (kp) => {
const process = createProcess(0);
Object.assign(process, { gain, tau, theta });
process.reset(0);
const final = (kp * gain) / (1 + kp * gain); // where a stable P-only loop settles after a unit step
let early = 0;
let late = 0;
let previous = 0;
const crossings = [];
for (let n = 0, t = 0; t < duration; n++, t = n * DT) {
const y = process.step(kp * (1 - process.y)); // no output limits: Ku is a property of the linear loop
if (!Number.isFinite(y)) return { ratio: Infinity, period: NaN };
const deviation = y - final;
if (t > duration / 3 && t <= (2 * duration) / 3) early = Math.max(early, Math.abs(deviation));
if (t > (2 * duration) / 3) late = Math.max(late, Math.abs(deviation));
if (t > duration / 3 && previous < 0 && deviation >= 0) crossings.push(t);
previous = deviation;
}
const period = crossings.length > 1 ? (crossings[crossings.length - 1] - crossings[0]) / (crossings.length - 1) : NaN;
if (late < 1e-9) return { ratio: 0, period }; // decayed to nothing: below Ku
return { ratio: late / early, period };
};
let low = 0.01;
let high = 100000;
for (let k = 0; k < 40; k++) {
const mid = Math.sqrt(low * high);
if (trial(mid).ratio >= 1) high = mid;
else low = mid;
}
return { ku: Math.sqrt(low * high), tu: trial(high).period };
}
// --- Step response metrics, measured live against the new setpoint ---
function createStepMetrics() {
let m = null;
return {
start(t, y, setpoint, previousSetpoint) {
// A step made before the last one finished, with the PV already near the new setpoint, can't be measured
const tooSmall = Math.abs(setpoint - y) < 0.5 * Math.abs(setpoint - previousSetpoint);
m = { t0: t, y0: y, setpoint, t10: null, t90: null, peak: 0, lastOutside: t, frozen: tooSmall, tooSmall };
},
freeze() {
if (m) m.frozen = true; // a disturbance would spoil the step metrics
},
update(t, y) {
if (!m || m.frozen) return;
const change = m.setpoint - m.y0;
if (change === 0) return;
const fraction = (y - m.y0) / change;
if (m.t10 === null && fraction >= 0.1) m.t10 = t;
if (m.t90 === null && fraction >= 0.9) m.t90 = t;
m.peak = Math.max(m.peak, fraction - 1);
if (Math.abs(y - m.setpoint) > 0.02 * Math.abs(change)) m.lastOutside = t; // 2% settling band
},
read(t) {
if (!m) return null;
const settled = t - m.lastOutside > 10; // inside the band for 10 s
if (m.tooSmall) return { tooSmall: true };
return {
tooSmall: false,
riseTime: m.t10 !== null && m.t90 !== null ? m.t90 - m.t10 : null,
overshoot: 100 * m.peak,
settlingTime: settled ? m.lastOutside - m.t0 : null,
frozen: m.frozen,
change: m.setpoint - m.y0
};
}
};
}
// --- The charts: setpoint and process variable on top, controller output and its P, I and D parts below ---
const theme = new SciChartJsNavyTheme();
const group = new SciChartVerticalGroup(); // lines up the two charts' axes
const capacity = (WINDOW * 2) / (DT * RECORD_EVERY); // keep two windows, so you can pan back after pausing
async function trendChart(div, yTitle, yRange, lines) {
const { sciChartSurface, wasmContext } = await SciChartSurface.create(div, { theme });
const xAxis = new NumericAxis(wasmContext, {
axisTitle: "Time (s)",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(0, WINDOW),
labelPrecision: 0
});
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: yTitle,
axisAlignment: EAxisAlignment.Left,
visibleRange: yRange,
autoRange: EAutoRange.Never,
labelPrecision: 0
})
);
const series = lines.map(({ name, colour, thickness = 2, dash }) => {
const dataSeries = new XyDataSeries(wasmContext, { dataSeriesName: name, fifoCapacity: capacity, isSorted: true, containsNaN: false });
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, { dataSeries, stroke: colour, strokeThickness: thickness, strokeDashArray: dash })
);
return dataSeries;
});
sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true, placement: ELegendPlacement.TopLeft, orientation: ELegendOrientation.Horizontal }),
new CursorModifier({ showTooltip: true, showYLine: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);
group.addSurfaceToGroup(sciChartSurface);
return { sciChartSurface, xAxis, series };
}
const pvChart = await trendChart(ui.pvDiv, "Process (%)", new NumberRange(20, 85), [
{ name: "Setpoint (SP)", colour: "#F48420", dash: [6, 4] },
{ name: "Process variable (PV)", colour: "#50C7E0", thickness: 2.5 }
]);
const coChart = await trendChart(ui.coDiv, "Output (%)", new NumberRange(-40, 140), [
{ name: "Controller output (CO)", colour: "#FFFFFF", thickness: 2.5 },
{ name: "P", colour: "#3BD16F", thickness: 1.5 },
{ name: "I", colour: "#E36FD4", thickness: 1.5 },
{ name: "D", colour: "#F6E05E", thickness: 1.5 }
]);
const limitLine = new HorizontalLineAnnotation({
y1: 100,
stroke: "#EF5350",
strokeThickness: 1.5,
strokeDashArray: [4, 4],
showLabel: true,
labelPlacement: ELabelPlacement.TopRight,
labelValue: "Output limit",
axisLabelFill: "#EF5350"
});
coChart.sciChartSurface.annotations.add(limitLine);
const [spSeries, pvSeries] = pvChart.series;
const [coSeries, pSeries, iSeries, dSeries] = coChart.series;
// --- The simulation ---
let random = 1977; // seeded noise, so the demo behaves the same every time
const noise = () => {
random = (random * 16807) % 2147483647;
const u1 = random / 2147483647;
random = (random * 16807) % 2147483647;
return Math.sqrt(-2 * Math.log(u1)) * Math.cos((2 * Math.PI * random) / 2147483647);
};
const process = createProcess(SETPOINTS[0]);
const pid = createPid();
pid.reset(SETPOINTS[0]); // start in steady state at 40%: the I term holds the output there
const metrics = createStepMetrics();
let setpoint = SETPOINTS[0];
let n = 0; // steps simulated
let paused = false;
let lastZn = null;
const buffer = { t: [], sp: [], pv: [], co: [], p: [], i: [], d: [] };
const recentPv = []; // the last 5 s of recorded PV, for the steady-state error
function stepSetpoint() {
const previous = setpoint;
setpoint = setpoint === SETPOINTS[0] ? SETPOINTS[1] : SETPOINTS[0];
metrics.start(n * DT, process.y, setpoint, previous);
}
function simulate(steps) {
for (let k = 0; k < steps; k++, n++) {
const t = n * DT;
if (n === 200) stepSetpoint(); // a first setpoint step at 2 s
const measured = process.y + 0.1 * noise(); // 0.1% measurement noise
const { u, p, i, d } = pid.update(setpoint, measured);
process.step(u);
metrics.update(t, process.y); // measured on the noise-free PV, so noise doesn't inflate the overshoot
if (n % RECORD_EVERY === 0) {
for (const [key, value] of [["t", t], ["sp", setpoint], ["pv", measured], ["co", u], ["p", p], ["i", i], ["d", d]]) buffer[key].push(value);
recentPv.push(process.y);
if (recentPv.length > 50) recentPv.shift();
}
}
if (buffer.t.length === 0) return;
spSeries.appendRange(buffer.t, buffer.sp);
pvSeries.appendRange(buffer.t, buffer.pv);
coSeries.appendRange(buffer.t, buffer.co);
pSeries.appendRange(buffer.t, buffer.p);
iSeries.appendRange(buffer.t, buffer.i);
dSeries.appendRange(buffer.t, buffer.d);
for (const key of Object.keys(buffer)) buffer[key].length = 0;
const now = n * DT;
const range = new NumberRange(Math.max(0, now - WINDOW), Math.max(WINDOW, now));
pvChart.xAxis.visibleRange = range;
coChart.xAxis.visibleRange = range;
}
function showReadout() {
const t = n * DT;
const m = metrics.read(t);
const fmt = (value, unit, digits = 1) => (value === null ? "–" : `${value.toFixed(digits)} ${unit}`);
// Steady-state error: the setpoint minus the average PV over the last 5 s
const average = recentPv.length ? recentPv.reduce((a, b) => a + b, 0) / recentPv.length : process.y;
const steadyError = setpoint - average;
const lines = [`Last setpoint step${m && m.frozen && !m.tooSmall ? " (until the disturbance)" : ""}`];
if (m && m.tooSmall) {
lines.push("Not measured: the PV was still close to the new setpoint. Wait for the loop to settle, then step again.");
} else {
lines.push(`Rise time (10–90%): ${fmt(m && m.riseTime, "s")}`);
lines.push(`Overshoot: ${m ? `${m.overshoot.toFixed(1)}%` : "–"}`);
lines.push(`Settling time (2%): ${m && m.settlingTime !== null ? fmt(m.settlingTime, "s") : m ? "settling…" : "–"}`);
}
lines.push(`Steady-state error now: ${steadyError.toFixed(2)}%`, "", `SP ${setpoint}% · PV ${process.y.toFixed(1)}%`);
if (lastZn) {
lines.push(
"",
`Ziegler–Nichols: Ku = ${lastZn.ku.toFixed(2)}, Tu = ${lastZn.tu.toFixed(2)} s, ` +
`so Kp = ${lastZn.kp.toFixed(2)}, Ki = ${lastZn.ki.toFixed(2)}/s, Kd = ${lastZn.kd.toFixed(2)} s`
);
}
ui.panel.textContent = lines.join("\n"); // plain text, one line per metric
}
simulate(Math.round(30 / DT)); // start with 30 s of history, including a setpoint step at 2 s
// Run about 60 times a second; each tick simulates the process time that has passed, SPEED times faster
let lastTime = performance.now();
let carry = 0;
let ticks = 0;
const timer = setInterval(() => {
const time = performance.now();
const due = Math.min(((time - lastTime) / 1000) * SPEED, 0.5) / DT + carry;
lastTime = time;
if (paused) return;
const steps = Math.floor(due);
carry = due - steps;
simulate(steps);
if (++ticks % 6 === 0) showReadout(); // ten readout updates a second is plenty
}, 16);
pvChart.sciChartSurface.addDeletable({ delete: () => clearInterval(timer) });
// --- The controls ---
const bindSlider = (id, format, apply) => {
const input = ui.input(id);
const update = () => {
const value = Number(input.value);
ui.output(id).textContent = format(value);
apply(value);
};
input.addEventListener("input", update);
update();
return input;
};
const kpInput = bindSlider("kp", (v) => v.toFixed(2), (v) => (pid.kp = v));
const kiInput = bindSlider("ki", (v) => `${v.toFixed(2)}/s`, (v) => (pid.ki = v));
const kdInput = bindSlider("kd", (v) => `${v.toFixed(2)} s`, (v) => (pid.kd = v));
bindSlider("gain", (v) => v.toFixed(1), (v) => (process.gain = v));
bindSlider("tau", (v) => `${v.toFixed(1)} s`, (v) => (process.tau = v));
bindSlider("theta", (v) => `${v.toFixed(1)} s`, (v) => {
process.theta = v;
process.resizeDelay();
});
bindSlider("umax", (v) => `${v}%`, (v) => {
pid.uMax = v;
limitLine.y1 = v;
});
const dModeSelect = ui.input("dmode");
dModeSelect.addEventListener("change", () => (pid.dOnMeasurement = dModeSelect.value === "measurement"));
const antiWindupCheckbox = ui.input("antiwindup");
antiWindupCheckbox.addEventListener("change", () => (pid.antiWindup = antiWindupCheckbox.checked));
ui.input("step").addEventListener("click", stepSetpoint);
const disturbButton = ui.input("disturb");
disturbButton.addEventListener("click", () => {
process.load = process.load === 0 ? DISTURBANCE : 0;
disturbButton.textContent = process.load === 0 ? "Add load disturbance" : "Remove load disturbance";
metrics.freeze();
});
const pauseButton = ui.input("pause");
const setPaused = (value) => {
paused = value;
pauseButton.textContent = paused ? "Resume" : "Pause";
};
pauseButton.addEventListener("click", () => setPaused(!paused));
// Zooming or panning pauses the trend, so the live update doesn't undo it
for (const surface of [pvChart.sciChartSurface, coChart.sciChartSurface]) {
const pauseForZoom = () => setPaused(true);
surface.domChartRoot.addEventListener("wheel", pauseForZoom);
surface.domChartRoot.addEventListener("pointerdown", pauseForZoom);
}
// Ziegler–Nichols: find Ku and Tu for the current process, apply the classic PID rule, then step the setpoint
ui.input("zn").addEventListener("click", () => {
const { ku, tu } = findUltimateGain(process.gain, process.tau, process.theta);
const kp = 0.6 * ku;
const ti = tu / 2; // integral time
const td = tu / 8; // derivative time
lastZn = { ku, tu, kp, ki: kp / ti, kd: kp * td };
for (const [input, value] of [[kpInput, lastZn.kp], [kiInput, lastZn.ki], [kdInput, lastZn.kd]]) {
input.value = String(value); // the sliders clamp values beyond their range
input.dispatchEvent(new Event("input"));
}
setPaused(false);
stepSetpoint();
showReadout();
});
showReadout();
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
NumberRange,
EAxisAlignment,
FastLineRenderableSeries,
XyDataSeries,
LegendModifier,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { axisTitle: "Process (%)", axisAlignment: EAxisAlignment.Left, visibleRange: new NumberRange(0, 100) })
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { id: "output", axisTitle: "Output (%)", axisAlignment: EAxisAlignment.Right, visibleRange: new NumberRange(0, 100) })
);
// Logged samples from your controller: time (s), setpoint, process variable and controller output (%)
const { time, setpoint, processVariable, output } = getYourControlLoopData();
const line = (name: string, y: number[], stroke: string, extra = {}) =>
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: time, yValues: y, dataSeriesName: name }),
stroke,
strokeThickness: 2,
...extra
});
sciChartSurface.renderableSeries.add(
line("Setpoint", setpoint, "#F48420", { strokeDashArray: [6, 4] }),
line("Process variable", processVariable, "#50C7E0"),
line("Controller output", output, "#FFFFFF", { yAxisId: "output" })
);
sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const ControlLoopChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 450 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
NumberRange,
EAxisAlignment,
FastLineRenderableSeries,
XyDataSeries,
LegendModifier,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
@Component({
selector: "app-control-loop-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 450px"></scichart-angular>`
})
export class ControlLoopChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { axisTitle: "Process (%)", axisAlignment: EAxisAlignment.Left, visibleRange: new NumberRange(0, 100) })
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { id: "output", axisTitle: "Output (%)", axisAlignment: EAxisAlignment.Right, visibleRange: new NumberRange(0, 100) })
);
// Logged samples from your controller: time (s), setpoint, process variable and controller output (%)
const { time, setpoint, processVariable, output } = getYourControlLoopData();
const line = (name: string, y: number[], stroke: string, extra = {}) =>
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: time, yValues: y, dataSeriesName: name }),
stroke,
strokeThickness: 2,
...extra
});
sciChartSurface.renderableSeries.add(
line("Setpoint", setpoint, "#F48420", { strokeDashArray: [6, 4] }),
line("Process variable", processVariable, "#50C7E0"),
line("Controller output", output, "#FFFFFF", { yAxisId: "output" })
);
sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
- Each trend is a
FastLineRenderableSeriesover anXyDataSerieswithfifoCapacity, so old samples drop off automatically as new ones arrive; the demo sets the time axis'svisibleRangeto the last 60 seconds after each update. - The two charts share one time window, and a
SciChartVerticalGrouplines up their axes so the setpoint step and the output's response sit directly above each other. - The output limit is a
HorizontalLineAnnotationthat moves with the Output limit slider. - A timer runs the simulation and appends the new samples in one
appendRangecall per series, about 60 times a second;addDeletablestops the timer when the chart is deleted.
See it in the demo app: JavaScript real-time chart · React real-time chart · Angular real-time chart, and for linked charts that pan and zoom together, JavaScript synchronised charts · React synchronised charts · Angular synchronised charts.
Go deeper: SciChart.js line series documentation, real-time updates and FIFO data series, synchronising multiple charts and the horizontal line annotation. Our guides to the strip chart and the low-pass filter cover scrolling trends and the filter used on the D term. For how industry uses SciChart, see the HMI and SCADA and instrumentation pages.
Frequently asked questions
What does a PID controller do?
A PID controller holds a measured quantity, such as a temperature, a pressure or a motor speed, at a target value called the setpoint. Many times a second it subtracts the measurement from the setpoint to get the error, and sets its output (a heater's power, a valve's opening, a motor's voltage) from three terms: proportional to the error now, to the error added up over time, and to how fast the error is changing.
How do you tune a PID controller?
Start with the integral and derivative gains at zero. Raise the proportional gain until the loop responds quickly to a setpoint step with a little overshoot, then add integral gain until the offset disappears in a reasonable time without slow oscillation. Add derivative gain last, only if the loop overshoots and the measurement is clean, to damp it. Make one change at a time and test each with a small setpoint step and a load disturbance. Ziegler–Nichols or lambda tuning give a starting point from a measured test.
What is the Ziegler–Nichols tuning method?
The Ziegler–Nichols closed-loop method, published in 1942, finds the ultimate gain Ku, the proportional-only gain at which the loop oscillates with a steady amplitude, and the period Tu of that oscillation. A PID controller then gets Kp = 0.6 Ku, an integral time of Tu/2 and a derivative time of Tu/8. The rules aim for a quarter-amplitude decay, so they give an aggressive, oscillatory response that usually needs detuning.
What are rise time, overshoot and settling time?
They describe a step response. Rise time is how long the output takes to go from 10% to 90% of the step. Overshoot is how far it peaks beyond the new value, as a percentage of the step. Settling time is how long after the step it takes to enter, and stay inside, a band around the final value, usually plus or minus 2%. Steady-state error is the gap left between the setpoint and the output once everything has settled.
What is integral windup?
Integral windup happens when the controller's output hits a limit, such as a valve fully open, while the error persists. The integral term keeps adding up error that the saturated actuator can't act on, and when the process finally reaches the setpoint the oversized integral holds the output high, causing a large overshoot. Anti-windup stops or bleeds off the integration while the output is saturated.
How do I simulate and chart a PID loop in JavaScript?
Write the process as a difference equation (for a first-order process with dead time, an Euler step plus a buffer for the delay) and the PID as a function called once per sample with the setpoint and the measurement. Run both in a timer, append each sample of setpoint, process variable and controller output to line series with a FIFO capacity, and scroll the time axis. SciChart.js does this with FastLineRenderableSeries and XyDataSeries in plain JavaScript, React or Angular.
Sources
- Ziegler, J. G. and Nichols, N. B. (1942), Optimum settings for automatic controllers. Transactions of the ASME, 64, 759–768. The closed-loop and reaction-curve tuning rules.
- Callender, A., Hartree, D. R. and Porter, A. (1936), Time-lag in a control system. Philosophical Transactions of the Royal Society A, 235. Early published tuning rules for controllers with dead time.
- Åström, K. J. and Murray, R. M. (2021), Feedback Systems: An Introduction for Scientists and Engineers, 2nd edition, Princeton University Press (free online). Step response specifications, PID control, Ziegler–Nichols tuning, relay feedback, windup, derivative filtering and setpoint weighting.
- Åström, K. J. and Hägglund, T. (2006), Advanced PID Control, ISA. Controller forms, anti-windup, the relay autotuner and tuning rules.
- Skogestad, S. (2003), Simple analytic rules for model reduction and PID controller tuning. Journal of Process Control, 13(4), 291–309. The SIMC (lambda-style) rules for FOPDT models.
- Cohen, G. H. and Coon, G. A. (1953), Theoretical consideration of retarded control. Transactions of the ASME, 75, 827–834.
- Desborough, L. and Miller, R. (2002), Increasing customer value of industrial control performance monitoring. Chemical Process Control VI, AIChE Symposium Series 98(326), 169–189. Reports Honeywell's survey of 11,000 industrial controllers.
- Ogata, K. (2010), Modern Control Engineering, 5th edition, Pearson. Transient response specifications and the second-order overshoot formula.