# PID control

A PID controller adds an integral and a derivative term to proportional feedback. This page adds each term in turn to a simulated heater, and shows what each one changes.

[`Download this page as a notebook`](https://dev.nominal.io/learning/_downloads/a7058c6c2a0585c83402eb9b0bd04aca/pid-control.md) to run its code in JupyterLab. [Running the notebooks](https://dev.nominal.io/learning/guides/notebooks/running.md) explains how to set it up. It uses the heater from [Introduction to control](https://dev.nominal.io/learning/guides/introduction-to-control.md).

## The three terms

“Proportional-integral-derivative (PID) control is by far the most common way of using feedback in engineering systems.”[[1]](https://dev.nominal.io/learning/guides/pid-control.md#fbs-pid) A PID controller sets its output from the error, the setpoint minus the measurement, as the sum of three terms:

- **Proportional.** Depends only on the present error. Raising its gain speeds up the response, but too much gain makes the process variable oscillate.[[2]](https://dev.nominal.io/learning/guides/pid-control.md#ni-pid)
- **Integral.** Sums the error over time, so it keeps pushing until no error is left. It removes steady-state error, but increases overshoot.[[2]](https://dev.nominal.io/learning/guides/pid-control.md#ni-pid)
- **Derivative.** Pushes back when the process variable is changing fast, which reduces overshoot. It’s very sensitive to noise in the measurement, so most real systems use only a little of it.[[2]](https://dev.nominal.io/learning/guides/pid-control.md#ni-pid)

## Adding the terms

This controller runs every `dt` seconds. It keeps a running sum of the error for the integral term and the previous error for the derivative term, and limits its output to 0 to 100 %. It stops adding to the sum while its output is limited, so the integral term can’t wind up. The heater has a time constant of 8 s, and the room cools from 20 °C to 10 °C at 20 s. The measurement has 0.1 °C of noise. The process is made up for the simulation:

```ipython3
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from learning.style import set_matplotlib_style

set_matplotlib_style()
```

```ipython3
dt = 0.05  # s per control cycle
t = np.arange(0, 40, dt)
setpoint = 50.0  # °C

class PID:
    """A PID controller with its output limited to 0 to 100 %."""

    def __init__(self, kp, ki=0.0, kd=0.0):
        self.kp, self.ki, self.kd = kp, ki, kd
        self.integral = 0.0
        self.last_error = 0.0

    def update(self, setpoint, measured):
        error = setpoint - measured
        derivative = (error - self.last_error) / dt
        self.last_error = error
        integral = self.integral + error * dt
        output = self.kp * error + self.ki * integral + self.kd * derivative
        if 0 <= output <= 100:  # add to the sum only while the output isn't limited
            self.integral = integral
        return float(np.clip(output, 0, 100))

def simulate(controller, seed=1):
    """Run the heater, and return each cycle's temperature and power."""
    rng = np.random.default_rng(seed)
    temperature = 20.0
    temps, powers = [], []
    for time in t:
        room = 20.0 if time < 20 else 10.0  # °C: the disturbance
        power = controller.update(setpoint, temperature + rng.normal(0, 0.1))  # %
        temperature += dt * (-(temperature - room) + 0.8 * power) / 8.0
        temps.append(temperature)
        powers.append(power)
    return np.array(temps), np.array(powers)

gains = {
    "P": PID(kp=10),
    "PI": PID(kp=10, ki=8),
    "PID": PID(kp=10, ki=8, kd=2),
}
results = {name: simulate(c) for name, c in gains.items()}

fig, (top, bottom) = plt.subplots(2, 1, sharex=True)
top.axhline(setpoint, color="0.5", linestyle="--")
for name, (temps, powers) in results.items():
    top.plot(t, temps, label=name)
    bottom.plot(t, powers)
top.set_ylabel("Temperature (°C)")
top.legend()
bottom.set_ylabel("Heater power (%)")
bottom.set_xlabel("Time (s)")
plt.show()

pd.DataFrame(
    {
        name: {
            "peak before 20 s (°C)": temps[: int(20 / dt)].max(),
            "temperature at 40 s (°C)": temps[-1],
            "output noise, last 5 s (% std)": powers[-int(5 / dt) :].std(),
        }
        for name, (temps, powers) in results.items()
    }
).round(1)
```

![../../_images/152598f581e0612b5a304246e0e633bcc3d7d545f49f02dbf49934f153de02c7.svg](https://dev.nominal.io/learning/_images/152598f581e0612b5a304246e0e633bcc3d7d545f49f02dbf49934f153de02c7.svg)

|  | P | PI | PID |
| --- | --- | --- | --- |
| peak before 20 s (°C) | 46.7 | 51.2 | 51.6 |
| temperature at 40 s (°C) | 45.6 | 50.0 | 50.0 |
| output noise, last 5 s (% std) | 1.1 | 1.1 | 7.6 |

On this heater:

- **P** settles below the setpoint, and stays there.
- **PI** reaches the setpoint, including after the room cools. It overshoots it on the way up, as the table’s peak shows.
- **PID** barely changes the response, but its output is much noisier. The derivative term differentiates the noise in the measurement, as well as the signal.

The derivative term is meant to reduce overshoot,[[2]](https://dev.nominal.io/learning/guides/pid-control.md#ni-pid) but on this process it has little overshoot to reduce. [Control](https://dev.nominal.io/learning/guides/control.md) covers step responses, integral windup and loop rates.

## Tuning

Tuning means choosing the three gains. Classic methods such as Ziegler–Nichols tuning give starting values from a simple test of the process.[[2]](https://dev.nominal.io/learning/guides/pid-control.md#ni-pid)[[1]](https://dev.nominal.io/learning/guides/pid-control.md#fbs-pid) Record each attempt, with its gains, so you can compare them afterwards.

## In Nominal

Each tuning attempt is a test, so give each its own dataset, with its gains as properties. A property is a key-value pair stored with the dataset.[[3]](https://dev.nominal.io/learning/guides/pid-control.md#nominal-data-model) This code uploads the three runs above:

```python
from nominal.core import NominalClient

client = NominalClient.from_profile("default")

for name, controller in gains.items():
    # one CSV file for each attempt, with a "timestamp" column and the channels below
    dataset = client.create_dataset(
        f"Heater tuning: {name}",
        properties={
            "kp": str(controller.kp),
            "ki": str(controller.ki),
            "kd": str(controller.kd),
        },
    )
    dataset.add_tabular_data(f"tuning-{name}.csv", timestamp_column="timestamp", timestamp_type="iso_8601")
```

Then plot the attempts’ temperature channels in one [workbook](https://dev.nominal.io/learning/reference/glossary.md#workbook "Where you analyze time-series data in Nominal, in tabs and panels, after a test or live."), and compare their overshoot and settling time against the gains in each dataset’s properties.[[4]](https://dev.nominal.io/learning/guides/pid-control.md#nominal-client)

## Further reading

- [Control](https://dev.nominal.io/learning/guides/control.md), on tuning a dynamometer’s speed loop.
- K. J. Åström and R. M. Murray, [Feedback Systems: An Introduction for Scientists and Engineers](https://fbswiki.org/wiki/index.php/Main_Page), a free textbook, with a chapter on PID control.
- NI, [The PID Controller & Theory Explained](https://www.ni.com/en/shop/labview/pid-theory-explained.html).

## References

---

[1]
([1](https://dev.nominal.io/learning/guides/pid-control.md#id1),[2](https://dev.nominal.io/learning/guides/pid-control.md#id7))

K. J. Åström and R. M. Murray, [“PID Control”](https://www.cds.caltech.edu/~murray/books/AM08/pdf/fbs-pid_24Jul2020.pdf), chapter 11 of *Feedback Systems: An Introduction for Scientists and Engineers*, 2nd edition, version 3.1.5, 2020-07-24, Princeton University Press. Retrieved 2026-11-13.

[2]
([1](https://dev.nominal.io/learning/guides/pid-control.md#id2),[2](https://dev.nominal.io/learning/guides/pid-control.md#id3),[3](https://dev.nominal.io/learning/guides/pid-control.md#id4),[4](https://dev.nominal.io/learning/guides/pid-control.md#id5),[5](https://dev.nominal.io/learning/guides/pid-control.md#id6))

NI, [“The PID Controller & Theory Explained”](https://www.ni.com/en/shop/labview/pid-theory-explained.html), updated 2025-03-07. Retrieved 2026-11-12.

[[3](https://dev.nominal.io/learning/guides/pid-control.md#id8)]

Nominal, [“Data model core concepts”](https://dev.nominal.io/platform/data-model.md). Retrieved 2026-11-24.

[[4](https://dev.nominal.io/learning/guides/pid-control.md#id9)]

Nominal, `NominalClient.create_dataset` and `Dataset.add_tabular_data` in the [nominal](https://pypi.org/project/nominal/) Python client, version 1.186.0. Retrieved 2026-11-30.
