pid-rs
pid-rs copied to clipboard
Add time-aware PID control method (fixes #35)
Summary
Adds next_control_output_with_dt(measurement, dt) method to handle time intervals properly in PID calculations, resolving the mathematical inaccuracies mentioned in #35.
Problem Solved
Previously, the PID controller ignored actual time intervals (dt) when calculating:
-
Integral term: Was accumulating
error * kiinstead oferror * ki * dt -
Derivative term: Was calculating
measurement_change * kdinstead of(measurement_change / dt) * kd
This led to inconsistent behavior when:
- Update intervals changed
- Sensor sampling was irregular
- Real-time constraints caused timing variations
Solution
New Method
-
next_control_output_with_dt(measurement: T, dt: T) -> ControlOutput<T> - Mathematically accurate integral:
∫e(t)dt ≈ Σ(error × dt) - Mathematically accurate derivative:
de/dt = Δmeasurement / dt
Backwards Compatibility
- Existing
next_control_output()unchanged - now a thin wrapper calling new method withdt=1.0 - All existing tests pass
- No breaking changes to public API
Testing
Added comprehensive test coverage:
- [x]
integral_with_dt: Verifies proper time-weighted integration - [x]
derivative_with_dt: Verifies proper rate-of-change calculation - [x]
backwards_compatibility: Ensures existing behavior unchanged - [x]
irregular_intervals: Tests real-world irregular timing scenarios - [x] All 14 tests pass (13 existing + 4 new)