Building a PID Controller in Rust

For the past three months, I've been anchoring my skills around robotics, systems programming, embedded systems, and simulation. A PID controller was one of the projects I wanted to build while learning Rust.
I built PID Explorer: a desktop app that simulates a heated room and lets me change the controller gains, heater response, sensor noise, and outdoor temperature. Four plots expose the temperature, actuator response, commands, and individual PID contributions.
This post walks through the model, the Rust implementation, and measured experiments. I'm assuming you can read Rust; control theory starts from the beginning. The code is on GitHub.
Contents
- The feedback loop
- Modeling the room and heater
- Proportional control
- Integral control
- Output limits and windup
- Derivative control and filtering
- The Rust controller
- The simulation loop
- Making the behavior visible
- Performance metrics
- Controlled experiments
- What carries over to hardware
The Feedback Loop
The objective is to keep a room at 22°C. It starts at 19°C, with an outdoor temperature of 12°C. At 100 seconds, outside drops to 2°C. The heater must first warm the room, then compensate for the increased heat loss.
A fixed heater command could balance one outdoor condition and fail when it changes. Feedback instead measures the result and adjusts the command repeatedly:
The room and heater form the plant. The target is the setpoint. Outdoor temperature is a disturbance. The controller receives the measured temperature, not the outdoor temperature or the model's true temperature.
The starting calculation is signed error:
fn error(target: f64, current: f64) -> f64 {
target - current
}
At a target of 22°C, a measurement of 19°C gives an error of +3°C. A measurement of 23°C gives −1°C. Positive error calls for more heating; negative error calls for less.
PID combines three contributions into one request:
| Term | Input | Role |
|---|---|---|
| P: proportional | Current signed error | Respond immediately to the temperature mismatch |
| I: integral | Accumulated error over time | Supply the sustained command needed to remove offset |
| D: derivative | Rate of measured temperature change | Reduce demand during rapid warming and increase it during cooling |
An on/off thermostat switches between discrete states, often with separate on/off thresholds to avoid rapid switching. Here, the command varies continuously from zero to ten. Those are abstract command units; the simulator defines how they become heat.
Modeling the Room and Heater
A controller produces a command, but that number alone cannot tell us whether the room will reach its target. We need a plant model that converts commands into heat and heat into temperature. Keeping that model small lets me isolate how each controller setting changes the response.
The thermal model lives in simulation.rs. Its constants establish the units and operating conditions:
const TARGET_TEMPERATURE: f64 = 22.0;
const INITIAL_TEMPERATURE: f64 = 19.0;
const TIME_STEP_SECONDS: f64 = 1.0;
const HEATING_RATE_PER_COMMAND_UNIT: f64 = 0.1;
const OUTDOOR_TEMPERATURE: f64 = 12.0;
const HEAT_LOSS_COEFFICIENT: f64 = 0.02;
pub(crate) const MIN_COMMAND: f64 = 0.0;
pub(crate) const MAX_COMMAND: f64 = 10.0;
This is a simplified temperature model, not a calibrated building simulation. The coefficients already incorporate the effect of thermal capacity. There are no separate wall temperatures, spatial gradients, occupancy, or solar gains.
Heat loss and required heating
Even after the room reaches its target, it keeps exchanging heat with the outdoors. The heater must replace that loss just to hold the temperature steady. This gives the simulation a continuing demand instead of a target that can be reached once and left alone.
Environmental exchange is proportional to the indoor/outdoor temperature difference. The applied command becomes a desired heater warming rate:
let heat_loss_rate =
HEAT_LOSS_COEFFICIENT * (current_temp - outdoor_temperature);
let desired_warming_rate =
output.applied * HEATING_RATE_PER_COMMAND_UNIT;
Here, “heat loss” and “warming rate” describe contributions to temperature change in °C/s, rather than thermal power in watts. The heat-loss coefficient has units of inverse seconds; the command conversion has units of °C/s per command unit.
At equilibrium, actual heating must equal heat loss. At the target, the required commands are:
Before the disturbance:
After the disturbance:
Here is the heat-loss rate and is the equilibrium command.
Both are within the available range. Zero error still requires nonzero heating, which explains why a proportional-only controller with no bias cannot hold exactly at the target.
The heat-loss term is signed. If outside is warmer than inside, it becomes negative and warms the room. The UI permits outdoor temperatures up to 30°C, but the actuator can only heat. Holding 22°C against a sustained 30°C environment is therefore impossible in this model.
Heater lag
A command can change instantly in software; the heating effect need not follow instantly. A heater takes time to build up its output, and reducing its command can leave heat still arriving in the room. If the model skipped this delay, the controller could appear to reverse the warming much more quickly than this simulated actuator allows.
I represent that behavior by storing an actual warming rate separately from the desired rate. The time constant sets how quickly the gap between them closes. The heater's actual output approaches the desired warming rate with a first-order response:
let response_fraction =
1.0 - (-dt / settings.heater_time_constant).exp();
actual_warming_rate +=
(desired_warming_rate - actual_warming_rate) * response_fraction;
For a held input, one time constant closes about 63.2% of the initial gap. It does not complete the response. With a five-second time constant and one-second steps, each update closes about 18.13% of the remaining gap:
Starting from zero heater output with a desired rate of :
Here is the heater time constant and is the step duration.
Increasing the time constant to twenty seconds reduces that fraction to about 0.04877. Both increases and decreases become slower. A zero command does not immediately stop heat delivery: the heater rate decays, and the room can keep warming until heating falls below heat loss.
For positive time constants and elapsed time, this exponential update moves the heater toward the requested rate without overshooting it. It is the exact first-order actuator response for a held input over the step; it does not make the coupled room simulation exact.
Room temperature update
We now have two competing rates: heat delivered by the heater and heat exchanged with the environment. Their difference determines whether the room warms or cools; accumulating that difference over a time step produces the next modeled temperature. Sensor noise is added separately when the controller receives a reading.
The room advances by the net temperature rate times elapsed time:
fn step_temperature(
current: f64,
warming_rate: f64,
heat_loss_rate: f64,
dt: f64,
) -> f64 {
current + (warming_rate - heat_loss_rate) * dt
}
Heating at 0.3°C/s against loss of 0.2°C/s raises the room by 0.1°C over one second. Heating at 0.1°C/s under the same loss still lets it cool.
The simulator evaluates heat loss at the beginning of the step, updates the heater, then uses the updated heater rate to advance the room. That ordering is a discrete approximation. Changing the step size or update order can change the trajectory; a smooth plot alone does not establish numerical accuracy.
Proportional Control
The simplest starting rule is to ask for more heat when the room is farther below target. That gives us an immediate correction without remembering earlier measurements. P scales the current signed error into command units:
let current_error = error(target, measurement);
let proportional_command = self.settings.kp * current_error;
With an error of +3°C, Kp = 1 produces three command units; Kp = 4 produces twelve. In proportional-only control, the latter is clamped to ten. The gain's units are command units per degree Celsius.
Why an offset remains
At exactly 22°C, P requests zero. Once residual heater output decays below heat loss, the room cools. A positive error must develop to generate the command needed to balance that loss.
We can derive the equilibrium. Let r be target, T room temperature, and Tout outdoor temperature. Assume the heater has settled, noise is zero, and the equilibrium command is not saturated:
Substitute , so :
For this model, the predicted offsets are:
| Kp | 12°C outside | 2°C outside |
|---|---|---|
| 1 | 1.667°C | 3.333°C |
| 4 | 0.476°C | 0.952°C |
| 10 | 0.196°C | 0.392°C |
Increasing P reduces equilibrium error, but the equation says nothing about the transient. Heater lag means a strong command can still be delivering heat after the controller has reduced demand.
Saturation changes the response
Once the requested command exceeds ten, additional demand cannot reach the actuator:
// Illustrative proportional-only requests at a 3°C error.
let error = 3.0_f64;
let medium_request = 4.0 * error; // 12
let high_request = 10.0 * error; // 30
assert_eq!(medium_request.clamp(0.0, 10.0), 10.0);
assert_eq!(high_request.clamp(0.0, 10.0), 10.0);
Higher gain changes when the command leaves saturation and how it responds afterward. In the experiments below, it reduces final offset but increases overshoot. P, I, and D outputs add arithmetically; their effects on the trajectory are coupled through the plant.
Integral Control
The remaining offset gives us a reason to add memory. If the room stays slightly cold, we want the command to keep increasing even when that small error stops changing. Once the room reaches the target, the extra contribution must remain available to replace ongoing heat loss.
I retains error accumulated over time. A one-degree error lasting ten seconds contributes ten degree-seconds, provided integration is accepted throughout that interval.
The code distinguishes the candidate state from the committed state:
let candidate_accumulated_error =
self.accumulated_error + current_error * dt;
let candidate_command = proportional_command
+ self.settings.ki * candidate_accumulated_error
+ derivative_command;
if self.should_integrate(candidate_command, current_error) {
self.accumulated_error = candidate_accumulated_error;
}
let integral_command = self.settings.ki * self.accumulated_error;
accumulated_error stores °C·s; multiplying by ki produces command units. The gain therefore has units of command units per degree-second. should_integrate applies the anti-windup rule explained next.
Why elapsed time matters
Memory needs to represent how long the error persists, not just how many times the function is called. The following arithmetic isolates integration, assuming every increment is accepted:
// Illustrative calculation: fixed 3°C error, Ki = 2.
let mut accumulated_error = 0.0_f64;
let error = 3.0;
let ki = 2.0;
accumulated_error += error * 0.5; // 1.5 °C·s
assert_eq!(ki * accumulated_error, 3.0);
accumulated_error += error * 1.0; // 4.5 °C·s total
assert_eq!(ki * accumulated_error, 9.0);
Without dt, calling the method twice as often would accumulate twice as much error per second for the same readings. Including it expresses the intended time integral, although changing the sampling interval still changes the sampled feedback dynamics.
At zero current error, the stored integral does not vanish. It can maintain the output needed to balance heat loss. With Ki = 2, accumulated errors of one and two °C·s provide the two- and four-unit equilibrium commands required before and after the disturbance.
Memory can become a liability
While a slow heater is building up its output, the room can stay cold and keep contributing positive error. Reaching the target stops that accumulation, but it does not erase what was stored. The retained contribution can also exceed what the room currently needs. This example isolates P and I at the target; it is illustrative arithmetic, not a recorded sample:
let accumulated_error = 2.0_f64; // °C·s
let current_error = 0.0; // At the target
let kp = 4.0;
let ki = 2.0;
let proportional = kp * current_error; // 0 command units
let integral = ki * accumulated_error; // 4 command units
let requested = proportional + integral; // D omitted here
assert_eq!(requested, 4.0);
Four command units request 0.4°C/s, but holding 22°C with 12°C outdoors needs only 0.2°C/s. If delivered, the excess warms the room above target. Actual heating depends on the actuator's current state and lag.
Negative error can reduce the stored integral when the conditional-integration rule accepts the decrement. A large Ki makes each accumulated degree-second more influential; a slow heater leaves more time for error to persist before earlier commands take effect. Their interaction can produce overshoot or oscillation even with anti-windup enabled.
Stored error versus scaled output
The choice of what to store also determines what happens when a gain changes. Because the implementation stores unscaled error, changing Ki while retaining state would immediately change I:
// Hypothetical live retuning, not the app's behavior.
let accumulated_error = 2.0_f64;
let old_integral = 1.0 * accumulated_error; // 2 command units
let new_integral = 2.0 * accumulated_error; // 4 command units
The app avoids that scenario by recalculating the entire experiment. Its settings-change branch calls:
self.samples = simulate(&self.settings);
Inside simulate, controller construction starts fresh:
let mut controller = Pid::new(pid_settings, current_temp);
The constructor initializes accumulated error and filtered rate to zero. It initializes the previous measurement to the starting room temperature. Changing a slider therefore compares new runs from common initial conditions; it does not retune a live controller. The code may accumulate unscaled error while Ki is zero, but that state is discarded when a setting change creates the next run.
Output Limits and Windup
Accumulated error becomes especially troublesome when the heater is already at its limit. Asking for twenty command units cannot heat faster than asking for ten, but continued integration can store an even larger request. That excess can keep the output saturated after less heating is needed; this is integral windup.
To make that mismatch visible, the controller retains both its mathematical request and the constrained actuator command:
let requested_command =
proportional_command + integral_command + derivative_command;
let applied_command =
requested_command.clamp(self.settings.min_output, self.settings.max_output);
Clamping keeps the applied command within its bounds, but does not constrain integral state.
Conditional integration
Conditional integration checks the proposed state before committing it. With nonnegative gains, it rejects an increment when the resulting candidate command is above the upper limit with positive error, or below the lower limit with negative error. The previous command does not have to be saturated for this check to reject the next increment.
The candidate command includes the proposed integral increment. This helper decides whether to commit it:
fn should_integrate(&self, candidate_command: f64, error: f64) -> bool {
if !self.settings.anti_windup_enabled {
return true;
}
let would_wind_up_high =
candidate_command > self.settings.max_output && error > 0.0;
let would_wind_up_low =
candidate_command < self.settings.min_output && error < 0.0;
!would_wind_up_high && !would_wind_up_low
}
With positive Ki, positive error pushes I upward and negative error pushes it downward. At Ki = 0, changing stored error has no effect on I. A candidate exactly on a command boundary is accepted.
Reversing error often allows unwinding, but acceptance still follows both conditions above. A sufficiently large negative increment that puts the candidate below the lower limit is rejected rather than accepted merely because it reduced a previously high state.
A worked sequence
The distinction between trial state and retained state is easier to follow across several updates. This sequence shows an accepted increment, a rejected increment, and a later reduction in stored error.
With Kp = 1, Ki = 1, Kd = 0, and limits of zero and ten, the following sequence comes directly from the controller's anti-windup example. Stored error is in °C·s; trial values include the proposed integral increment:
| Stored error | Error | dt | Trial I | Trial output | Accepted? | Final I | Req. / applied |
|---|---|---|---|---|---|---|---|
| 0 | +2°C | 4 s | 8 | 10 | Yes | 8 | 10 / 10 |
| 8 | +5°C | 1 s | 13 | 18 | No | 8 | 13 / 10 |
| 8 | −1°C | 1 s | 7 | 6 | Yes | 7 | 6 / 6 |
In the second row, rejecting candidate accumulation leaves I at eight, but P still contributes five. The returned request is thirteen, not eighteen, and clamping remains necessary.
Conditional integration handles command saturation. It does not compensate for the gap between desired and actual heater rate while a command remains within its limits. It also does not guarantee stable tuning.
Derivative Control and Filtering
Two rooms can have the same temperature error while behaving differently: one might be warming rapidly, while the other is barely moving. P sees the same current error in both. A rate term gives the controller a way to reduce demand while the room is already moving quickly toward the target, before that motion becomes overshoot.
D responds to the estimated temperature rate. With positive Kd, a positive rate estimate produces a negative contribution and a negative estimate a positive one. When filtering is enabled, that estimate can lag a reversal in the measured temperature. The complete helper includes the filter between the raw difference and the returned command:
fn derivative_command(&mut self, measurement: f64, dt: f64) -> f64 {
let temperature_rate = (measurement - self.previous_temperature) / dt;
if self.settings.derivative_filter_time_constant == 0.0 {
self.filtered_temperature_rate = temperature_rate;
} else {
let response_fraction =
1.0 - (-dt / self.settings.derivative_filter_time_constant).exp();
self.filtered_temperature_rate +=
(temperature_rate - self.filtered_temperature_rate) * response_fraction;
}
-self.settings.kd * self.filtered_temperature_rate
}
A rise of 1°C in half a second gives a raw rate of 2°C/s. With Kd = 2 and filtering disabled, D is −4 command units. Kd has units of command units times seconds per degree Celsius.
D can damp the response by reducing demand during rapid warming. It measures a finite difference; it does not predict the future.
Derivative on measurement
Differentiation introduces a choice: track changes in the error or in the measurement. A sudden target change alters the error even when the room has not moved. Using the measurement keeps that target jump out of the derivative contribution.
The derivative is based on temperature rather than error. For a constant setpoint, these are equivalent up to sign:
Here is the measured temperature and is the target.
If the setpoint jumps, derivative on error also differentiates that jump. Derivative on measurement avoids this setpoint-induced kick. P and I can still respond to the changed error.
An illustrative call sequence using the existing API makes the distinction explicit:
let mut controller = Pid::new(settings, 19.0);
let first = controller.update(22.0, 19.0, 1.0);
let changed_target = controller.update(25.0, 19.0, 1.0);
assert_eq!(first.derivative, 0.0);
assert_eq!(changed_target.derivative, 0.0);
Here settings denotes valid PID settings, with filter state initially zero. The measurement stays unchanged, so D remains zero regardless of the target jump. The desktop simulator itself keeps the setpoint fixed at 22°C.
Noise and the filter tradeoff
The rate term is useful only to the extent that changing readings represent changing temperature. Real readings fluctuate, so reacting strongly to every difference can make the command fluctuate too. Sensor noise becomes apparent motion when consecutive readings are subtracted. For example, a stationary room measured first as 21.8°C and then 22.2°C produces:
The derivative contribution is in command units, with filtering disabled.
A shorter interval makes the same measurement difference produce a larger derivative estimate. Increasing Kd amplifies both physical changes and measurement noise.
The filter smooths the rate using the same exponential form as the actuator, but it represents controller signal processing rather than heater dynamics. A zero filter time constant explicitly bypasses smoothing. A larger value reduces abrupt changes and delays the response to genuine temperature movement.
For a time constant of 1 / ln(2) seconds and dt = 1, each update closes half the gap to the raw rate. Here Kd = 2, the previous measurement starts at 19°C, and the filtered rate starts at zero:
| Measurement | Raw rate | Filtered | D |
|---|---|---|---|
| 19 → 21°C | 2°C/s | 1°C/s | −2 |
| 21 → 21°C | 0°C/s | 0.5°C/s | −1 |
| 21 → 21°C | 0°C/s | 0.25°C/s | −0.5 |
The initial contribution is smaller than the unfiltered −4, but it leaves a tail. Filtering cannot remove noise without changing the derivative path's response.
Initial measurement
A difference needs two measurements, but the first update has no previous sample from the loop. The initialization policy therefore affects the first command. The constructor seeds derivative history from the initial room temperature:
Self {
settings,
accumulated_error: 0.0,
previous_temperature: initial_temperature,
filtered_temperature_rate: 0.0,
}
The first derivative estimate is zero with noise disabled. With noise enabled, the first measured temperature can differ from that true initial temperature and produce a nonzero derivative. A hardware controller would need to initialize from an appropriate sensor reading rather than assuming exact knowledge of the physical state.
The Rust Controller
The formulas now require information to survive between calls: accumulated error for I, the previous measurement for D, and the previous filtered rate for smoothing. Keeping these together in a controller instance makes each update advance one consistent history.
The controller owns its settings and three pieces of persistent state:
#[derive(Debug)]
pub(crate) struct Pid {
settings: PidSettings,
accumulated_error: f64,
previous_temperature: f64,
filtered_temperature_rate: f64,
}
PidSettings holds kp, ki, kd, output limits, the anti-windup flag, and the derivative filter time constant. Settings stay fixed during one simulation. The controller has no UI or random-number dependencies.
Each update returns the component contributions as well as the command:
#[derive(Debug, Clone)]
pub(crate) struct ControlOutput {
pub(crate) proportional: f64,
pub(crate) integral: f64,
pub(crate) derivative: f64,
pub(crate) requested: f64,
pub(crate) applied: f64,
}
The plant consumes applied; the other values expose how it was calculated. Returning them together lets the graphs inspect the same calculation instead of reconstructing controller internals afterward.
Update order
These calculations depend on both old and newly computed state. Their order determines whether D sees the previous measurement and whether I uses an accepted increment. The crate-visible entry point takes target, measurement, and elapsed time:
pub(crate) fn update(&mut self, target: f64, measurement: f64, dt: f64) -> ControlOutput
Its sequence is:
- Validate
dt, calculate error, update D, and calculate P. - Calculate the candidate accumulated error and candidate total command.
- Accept or reject the integral increment.
- Calculate final I, sum the terms, and clamp the output.
- Store the measurement for the next derivative calculation.
The history update must occur after differentiation:
let derivative_command = self.derivative_command(measurement, dt);
// P, conditional I, and output limiting occur here.
self.previous_temperature = measurement;
This is an excerpt with the intervening calculations omitted. Overwriting history first would make the measured difference zero. Similarly, final I must use committed state rather than the rejected candidate.
First update, end to end
Following one complete step connects the separate helpers and shows which values actually reach the plant. Use , , , and with noise disabled and anti-windup enabled. The target is 22°C; both the previous and current measurements are 19°C:
Since and , anti-windup rejects the increment. The accumulated error remains zero:
The request returned by the controller is twelve, not the rejected candidate of eighteen. With the default five-second heater time constant, initial heater rate of zero, and outdoor temperature of 12°C, the plant then advances:
Validation boundaries
The equations assume a meaningful elapsed time: D divides by it, while I accumulates over it. Invalid timing can therefore corrupt several terms at once. The update rejects invalid elapsed times:
assert!(dt.is_finite() && dt > 0.0, "dt must be finite and positive");
The constructor also requires a finite, nonnegative filter time constant. The simulation validates noise amplitude, heater time constant, and sample count. Gains, targets, measurements, and output-limit configurations are not exhaustively validated by the controller itself.
The UI constrains normal application inputs, but this is not a hardened general-purpose PID library. Reusing it behind external configuration or hardware readings would require explicit validation and failure behavior for those inputs.
The Simulation Loop
One controller update only chooses the next command. A trajectory comes from repeatedly measuring the plant, choosing a command, advancing the heater and room, and feeding the resulting temperature back into the controller. This loop connects the stateful pieces introduced above.
simulate creates fresh state and returns the complete trajectory as Vec<Sample>. The defaults are:
Self {
kp: 4.0,
ki: 2.0,
kd: 1.0,
disturbance: Disturbance {
starts_at: 100.0,
outdoor_temperature: 2.0,
},
heater_time_constant: 5.0,
anti_windup_enabled: true,
sensor_noise_amplitude: 0.1,
derivative_filter_time_constant: 0.0,
sample_count: 200,
}
Each iteration selects the outdoor condition using the beginning-of-step timestamp:
let time = (t - 1) as f64 * dt;
let outdoor_temperature = if time >= settings.disturbance.starts_at {
settings.disturbance.outdoor_temperature
} else {
OUTDOOR_TEMPERATURE
};
Measurement and repeatability
To study measurement error, the controller needs a sensor reading distinct from the model's true temperature. To compare settings fairly, it also helps to reuse the same random noise draws. A generator seeded once per run supplies uniform sensor noise:
let mut rng = StdRng::seed_from_u64(42);
Inside the loop:
let noise = rng.random_range(-1.0..=1.0) * settings.sensor_noise_amplitude;
let measured_temperature = current_temp + noise;
let output = controller.update(target_temp, measured_temperature, dt);
The controller sees the noisy measurement; the model retains true temperature separately. This noise model does not include bias, latency, quantization, or correlated errors.
Identical settings and dependency implementations reproduce the same run. Comparisons reuse the same random draws, although their true temperature trajectories can differ. A fixed seed supplies one repeatable realization, not evidence of robustness across all noise sequences. The reported experiments use rand 0.10.4.
Recording and advancing state
A plotted sample needs a consistent meaning: the state at the beginning of an interval is different from the state after applying its command. Recording those values deliberately prevents a one-step timing mismatch when interpreting a disturbance or heater response.
The exact order around the actuator update is:
let desired_warming_rate = output.applied * HEATING_RATE_PER_COMMAND_UNIT;
let sampled_warming_rate = actual_warming_rate;
actual_warming_rate +=
(desired_warming_rate - actual_warming_rate) * response_fraction;
let step_temp = step_temperature(current_temp, actual_warming_rate, heat_loss_rate, dt);
The sample records the old room and heater states alongside the command calculated from that step's measurement:
samples.push(Sample {
time,
target: target_temp,
temperature: current_temp,
measured_temperature,
output,
actual_warming_rate: sampled_warming_rate,
desired_warming_rate,
});
current_temp = step_temp;
At time zero, the plotted temperature is 19°C and actual heater rate is zero, even though the first command already requests heat. The first temperature advance appears at the next timestamp.
Similarly, the disturbance at time 100 changes heat loss during that step; its effect first appears in recorded temperature at time 101. With 200 samples, timestamps run from zero to 199. The final computed advance is not stored, so final error uses the state at 199 seconds.
The complete run is calculated immediately. One simulated second is not one second of wall-clock waiting, and the window's rendering rate does not determine controller timing. Changing sample count changes duration; the step remains fixed at one second.
Making the Behavior Visible
A temperature trace shows whether tracking is good, but it cannot explain why a run overshoots. The cause could involve stored integral demand, a saturated command, or heat still arriving after demand falls. Plotting the internal contributions and actuator behavior alongside temperature makes those possibilities distinguishable.
The desktop interface uses eframe/egui, egui_plot, and Phosphor icons. Its state separates current settings, current results, and a saved reference:
pub(crate) struct App {
settings: SimulationSettings,
samples: Vec<Sample>,
reference_samples: Option<Vec<Sample>>,
}
The four plots answer different questions:
| Plot | Signals | Inspect |
|---|---|---|
| Temperature | Actual, measured, target, reference | Offset, overshoot, noise, and recovery |
| Heater response | Desired and actual warming rate | Actuator lag after commands rise or fall |
| Command | Requested and applied output | When clamping prevents demand from reaching the actuator |
| Contributions | P, I, D | Which term sustains or changes the request |
For example, above-target temperature with positive demand may be explained by I outweighing negative P and D. A zero applied command with continued warming may instead be explained by residual heater output.
Linking plots
Diagnosing an event means inspecting the same instant across several plots. Each plot uses shared IDs to link horizontal navigation and cursor position, while keeping its own vertical scale:
.link_axis(egui::Id::unique(TIME_AXIS_GROUP), [true, false])
.link_cursor(egui::Id::unique(TIME_CURSOR_GROUP), [true, false])
This aligns the same instant across temperature, warming rate, and command without combining incompatible vertical units. The desktop app uses gold for target/requested values, blue for actual/applied values, and lavender for the reference; the article's charts use the site's dark olive and red palette.
Comparing runs
A slider change replaces the current trajectory, so comparing by memory makes small differences hard to judge. A saved reference keeps one run available while I change settings. Saving a reference clones the current trajectory:
if ui.button("Save reference").clicked() {
self.reference_samples = Some(self.samples.clone());
}
Subsequent setting changes replace samples, leaving the reference available. The temperature graph overlays the saved trace, and the scorecards show reference metrics. Saving again replaces it; Clear removes it; Reset restores defaults and clears the reference. References are kept only in memory.
Performance Metrics
Plots reveal the shape of a response; numbers make repeated comparisons easier. No single score captures both a brief large overshoot and a small error that lasts the entire run, so I measure peak overshoot, average error, final error, and time at the command limits separately.
Metrics use all recorded samples, independent of plot zoom. Temperature metrics evaluate actual temperature rather than sensor noise. The accumulation loop is:
let mut max_overshoot: f64 = 0.0;
let mut total_absolute_error = 0.0;
for sample in samples {
let difference = sample.temperature - sample.target;
max_overshoot = max_overshoot.max(difference);
total_absolute_error += difference.abs();
if sample.output.applied == MIN_COMMAND || sample.output.applied == MAX_COMMAND {
samples_at_limit += 1;
}
}
This excerpt omits the preceding samples_at_limit = 0 initialization and empty-input check. The full function returns None for an empty slice. For nonempty input, the final calculations are:
Some(Performance {
max_overshoot,
mean_absolute_error: total_absolute_error / samples.len() as f64,
final_absolute_error: (last_sample.target - last_sample.temperature).abs(),
output_limit_percentage: samples_at_limit as f64 / samples.len() as f64 * 100.0,
})
| Metric | Meaning | Limit |
|---|---|---|
| Maximum overshoot | Largest positive temperature deviation, or zero | Does not measure undershoot or its duration |
| Mean absolute error | Average distance from target | Combines warm-up, disturbance recovery, and later tracking |
| Final absolute error | Error at the last recorded state | A small value does not establish settling or stability |
| Time at output limits | Percentage of samples at either zero or ten | Neither command smoothness nor time at maximum heating alone |
Compare equal durations and conditions. Extending a well-behaved tail can reduce mean error without improving the earlier transient. Full heating during warm-up and zero heating above target can both be appropriate, so a lower limit percentage is not automatically better. Clamping produces exact endpoint values, making the equality checks meaningful here.
Controlled Experiments
The experiments connect each mechanism to an observable change. I start with proportional control, add integral action, then isolate actuator lag, anti-windup, and filtering. Each comparison below states what changes so the resulting difference has a specific interpretation.
These results come from the project's unchanged controller, simulation, and metric modules, called through an isolated command-line harness. Every run uses 200 one-second samples, starts at 19°C, targets 22°C, and changes outdoor temperature from 12°C to 2°C at time 100.
Heater τ is the heater time constant; noise is the sensor noise amplitude.
| Run | Kp | Ki | Kd | Heater τ | Noise | D filter | Anti-windup |
|---|---|---|---|---|---|---|---|
| P, low gain | 1 | 0 | 0 | 5 s | 0°C | 0 s | On |
| P, medium gain | 4 | 0 | 0 | 5 s | 0°C | 0 s | On |
| P, high gain | 10 | 0 | 0 | 5 s | 0°C | 0 s | On |
| PI | 4 | 2 | 0 | 5 s | 0°C | 0 s | On |
| Slow heater | 4 | 2 | 0 | 20 s | 0°C | 0 s | On |
| Windup | 4 | 2 | 0 | 20 s | 0°C | 0 s | Off |
| Noisy D | 4 | 2 | 5 | 5 s | ±0.5°C | 0 s | On |
| Filtered D | 4 | 2 | 5 | 5 s | ±0.5°C | 2 s | On |
| App defaults | 4 | 2 | 1 | 5 s | ±0.1°C | 0 s | On |
MAE is mean absolute error; final error is absolute error at the last sample. At limits counts samples at either command bound. Temperature metrics are rounded to three decimals:
| Run | Overshoot | MAE | Final error | At limits |
|---|---|---|---|---|
| P, low gain | 0.000°C | 2.549°C | 3.333°C | 0.0% |
| P, medium gain | 0.241°C | 0.771°C | 0.952°C | 5.0% |
| P, high gain | 0.984°C | 0.406°C | 0.392°C | 11.0% |
| PI | 1.360°C | 0.508°C | 0.260°C | 6.0% |
| Slow heater | 2.824°C | 1.143°C | 0.643°C | 40.0% |
| Windup | 9.798°C | 5.182°C | 9.798°C | 99.0% |
| Noisy D | 1.559°C | 0.389°C | 0.249°C | 28.5% |
| Filtered D | 1.600°C | 0.377°C | 0.107°C | 13.0% |
| App defaults | 1.815°C | 0.481°C | 0.533°C | 5.5% |
Proportional-only control
First, how much offset can P remove on its own, and what happens during warm-up as its gain increases? Set I, D, and noise to zero, then compare P gains of one, four, and ten. An equivalent configuration in Rust is:
let settings = SimulationSettings {
kp: 4.0, // Repeat with 1.0 and 10.0.
ki: 0.0,
kd: 0.0,
sensor_noise_amplitude: 0.0,
..SimulationSettings::default()
};
Final errors of 3.333°C, 0.952°C, and 0.392°C match the equilibrium predictions. Overshoot increases from zero to 0.241°C and 0.984°C. Larger gain reduces the offset but makes the transient more aggressive.
A run can overshoot during warm-up and settle below the target later. Those observations describe different parts of the response, not conflicting results.
Adding I and slowing the heater
Next, does integral action reduce the remaining error, and how does its behavior change when the heater responds more slowly? Use Kp = 4, Ki = 2, and no derivative or noise. Compare five- and twenty-second heater time constants:
let settings = SimulationSettings {
kp: 4.0,
ki: 2.0,
kd: 0.0,
sensor_noise_amplitude: 0.0,
heater_time_constant: 5.0, // Repeat with 20.0.
..SimulationSettings::default()
};
Against the P-only Kp = 4 run, adding I reduces final error from 0.952°C to 0.260°C, while increasing overshoot from 0.241°C to 1.360°C. That finite endpoint is not a test of asymptotic zero error.
Slowing the heater increases overshoot again, to 2.824°C, and mean error from 0.508°C to 1.143°C. Anti-windup is still enabled. The remaining overshoot demonstrates that handling command saturation does not remove actuator lag or guarantee good tuning.
Disabling anti-windup
To isolate the effect of rejecting integral increments during saturation, keep the slow-heater settings and change only the flag:
let settings = SimulationSettings {
kp: 4.0,
ki: 2.0,
kd: 0.0,
heater_time_constant: 20.0,
sensor_noise_amplitude: 0.0,
anti_windup_enabled: false,
..SimulationSettings::default()
};
Maximum overshoot rises from 2.824°C to 9.798°C; mean error rises from 1.143°C to 5.182°C. The run ends almost ten degrees above target. Integration during saturation stores demand the actuator cannot deliver, then delays reversal while the heater also responds slowly.
The disabled run spends 99% of samples at a command limit. This includes both fully on and fully off; it does not mean 99% at maximum heat.
Noisy derivative, then filtering
The next comparison asks whether smoothing a noisy rate estimate reduces abrupt controller activity, and what tracking tradeoff accompanies it. Use a deliberately large derivative gain and compare filter time constants of zero and two seconds:
let settings = SimulationSettings {
kp: 4.0,
ki: 2.0,
kd: 5.0,
sensor_noise_amplitude: 0.5,
derivative_filter_time_constant: 0.0, // Repeat with 2.0.
..SimulationSettings::default()
};
Filtering lowers time at limits from 28.5% to 13.0%, mean error from 0.389°C to 0.377°C, and final error from 0.249°C to 0.107°C. Overshoot increases slightly, from 1.559°C to 1.600°C.
Both runs use the same random draws, but their closed-loop temperature trajectories differ. The plot shows the resulting D contributions, not a single fixed input processed two ways. Filtering smooths the derivative path while delaying meaningful rate changes; it does not improve every tracking metric.
Disturbance recovery and defaults
Warm-up tests reaching a target from a cold start. The outdoor change tests a different demand: adjusting the heating needed to maintain that same target. The outdoor change increases the steady heating requirement from two to four command units. P-only runs require larger error to generate that extra output. Integral-enabled controllers can change their retained contribution, subject to their dynamics and limits.
The default run includes Kd = 1 and ±0.1°C noise, unlike the noise-free PI comparison. Its 1.815°C overshoot and 0.533°C final error are baseline observations, not recommended tuning. Comparing it with PI changes multiple parameters, so the difference cannot be attributed to D alone.
What Carries Over to Hardware
The simulation gives the controller exact timing, known initial conditions, and a defined actuator response. Physical hardware has to establish or measure those conditions. That is where the same equations become part of a larger sensing and actuation system.
The implementation exposes decisions that also matter in robotics and embedded control, but the gains belong to this plant and sampling interval. A hardware adaptation would need to address:
| Area | Simulation | Hardware |
|---|---|---|
| Timing | Fixed one-second dt | Measurement timestamps, scheduling jitter, missed deadlines |
| Sensing | True temperature plus uniform noise | Calibration, bias, quantization, latency, invalid readings |
| Actuation | Command clamp and first-order lag | Current/voltage limits, dead zones, rate limits, discrete outputs |
| Startup | Known initial temperature | Valid initial measurement and controlled output enabling |
| Model accuracy | Room temperature and heater-rate states | Calibration, step-size convergence, additional physical states |
A sensor bias can make the controller hold the measured target while true temperature is wrong. I corrects measured error, not an unknown calibration error. Downstream actuator limits likewise need to be reflected in anti-windup behavior; the current rule only sees the explicit command clamp.
The model already has two evolving plant states. Adding a wall temperature or a separate physical heater temperature would extend it, while checking smaller time steps against a reference solution would evaluate the existing discretization. Multiple noise seeds would test whether tuning conclusions survive beyond this one realization.
To run the project:
git clone https://github.com/sahmed007/pid.git
cd pid
cargo run --locked --release
Start with P only and noise disabled. Save a reference, change one setting, and inspect the command and heater plots alongside temperature. That connects a change in the code's calculation to a change in the system's behavior.
The full source code is available on GitHub.