diff --git a/src/lib/battery/battery.cpp b/src/lib/battery/battery.cpp index 766c147e61c..df728e30ef1 100644 --- a/src/lib/battery/battery.cpp +++ b/src/lib/battery/battery.cpp @@ -213,7 +213,17 @@ void Battery::updateAndPublishBatteryStatus(const hrt_abstime ×tamp) void Battery::updateDt(const hrt_abstime ×tamp) { if (_last_timestamp != 0) { - _dt = math::min((timestamp - _last_timestamp) / 1e6f, 2.f); // guard to a maximum 2 seconds dt + // _dt_discharge is the true, unclamped time delta: for the coulomb + // count in sumDischarged() below, using the real elapsed time is + // always more accurate than clamping it, even across an unusually + // long gap between updates (e.g. an update source that reports + // less often than every 2 seconds). + _dt_discharge = (timestamp - _last_timestamp) / 1e6f; + + // _dt is clamped to guard the numerical stability of the current + // average filter below, which assumes a roughly steady sample + // interval and should not see a single very large dt. + _dt = math::min(_dt_discharge, 2.f); } _last_timestamp = timestamp; @@ -221,10 +231,10 @@ void Battery::updateDt(const hrt_abstime ×tamp) float Battery::sumDischarged(float current_a) { - if (_dt > FLT_EPSILON && fabsf(current_a + 1.f) > FLT_EPSILON) { + if (_dt_discharge > FLT_EPSILON && fabsf(current_a + 1.f) > FLT_EPSILON) { // mAh since last loop: (current[A] * 1000 = [mA]) * (dt[s] / 3600 = [h]) // current = -1 means invalid current measurement - _discharged_mah_loop = (current_a * 1e3f) * (_dt / 3600.f); + _discharged_mah_loop = (current_a * 1e3f) * (_dt_discharge / 3600.f); _discharged_mah += _discharged_mah_loop; } diff --git a/src/lib/battery/battery.h b/src/lib/battery/battery.h index bcc9baa6d9e..f09f8f7984e 100644 --- a/src/lib/battery/battery.h +++ b/src/lib/battery/battery.h @@ -198,6 +198,7 @@ private: float _scale{1.f}; uint8_t _warning{battery_status_s::WARNING_NONE}; float _dt{0.f}; + float _dt_discharge{0.f}; // unclamped dt, used for the discharged_mah coulomb count float _capacity_mah{0.f}; hrt_abstime _last_timestamp{0}; bool _armed{false};