From 30e78141dba32cce0c31ddc9282166b1b478929c Mon Sep 17 00:00:00 2001 From: Balduin Date: Wed, 18 Mar 2026 15:28:21 +0100 Subject: [PATCH] fix(battery): Debounce battery connected state in battery library This robustifies against some communication flukes where a single 0V sample was given to the battery library, which would previously mark the battery disconnected immediately. Now we tolerate a given time of 0V samples (while not actually updating the voltage) before considering the battery disconnected. --- src/lib/battery/battery.cpp | 8 ++++++-- src/lib/battery/battery.h | 6 ++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/lib/battery/battery.cpp b/src/lib/battery/battery.cpp index 5fbcc6ac30..514da2450a 100644 --- a/src/lib/battery/battery.cpp +++ b/src/lib/battery/battery.cpp @@ -98,7 +98,10 @@ Battery::Battery(int index, ModuleParams *parent, const int sample_interval_us, void Battery::updateVoltage(const float voltage_v) { - _voltage_v = voltage_v; + if (voltage_v >= LITHIUM_BATTERY_RECOGNITION_VOLTAGE) { + _voltage_v = voltage_v; + _last_sufficient_voltage_timestamp = hrt_absolute_time(); + } } void Battery::updateCurrent(const float current_a) @@ -116,7 +119,8 @@ void Battery::updateBatteryStatus(const hrt_abstime ×tamp) updateDt(timestamp); // Require minimum voltage otherwise override connected status - if (_voltage_v < LITHIUM_BATTERY_RECOGNITION_VOLTAGE) { + // Tolerate a small number of low-voltage samples (common I2C comm failure) before disconnection + if (timestamp - _last_sufficient_voltage_timestamp > MAX_LOW_VOLTAGE_TIME_S * 1_s) { _connected = false; } diff --git a/src/lib/battery/battery.h b/src/lib/battery/battery.h index b432c80e27..2c19aa355c 100644 --- a/src/lib/battery/battery.h +++ b/src/lib/battery/battery.h @@ -134,8 +134,6 @@ public: void updateDt(const hrt_abstime ×tamp); protected: - static constexpr float LITHIUM_BATTERY_RECOGNITION_VOLTAGE = 2.1f; - struct { param_t v_empty; param_t v_charged; @@ -202,6 +200,10 @@ private: bool _vehicle_status_is_fw{false}; hrt_abstime _last_unconnected_timestamp{0}; + static constexpr float LITHIUM_BATTERY_RECOGNITION_VOLTAGE = 2.1f; + static constexpr float MAX_LOW_VOLTAGE_TIME_S = 0.2f; + hrt_abstime _last_sufficient_voltage_timestamp{0}; + // Internal Resistance estimation void updateInternalResistanceEstimation(const float voltage_v, const float current_a); void resetInternalResistanceEstimation(const float voltage_v, const float current_a);