pid-rs icon indicating copy to clipboard operation
pid-rs copied to clipboard

Add time-aware PID control method (fixes #35)

Open chantakan opened this issue 7 months ago • 0 comments

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 * ki instead of error * ki * dt
  • Derivative term: Was calculating measurement_change * kd instead 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 with dt=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)

chantakan avatar Sep 12 '25 08:09 chantakan