From 0126efe429223c2db3676446d1d2fb1bd5ca1684 Mon Sep 17 00:00:00 2001 From: marco <49691247+marcoSchr@users.noreply.github.com> Date: Fri, 22 Sep 2023 19:01:19 +0200 Subject: [PATCH] Fixed possible undeflow in battery charge level computation. Fix #192. We check if the battery is below minimum and, if so, assume that the charge is 0%. This to prevent an underflow which would result in the function returing a 100% charge level. --- openrtx/src/core/battery.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/openrtx/src/core/battery.c b/openrtx/src/core/battery.c index 88257300..88ba5b84 100644 --- a/openrtx/src/core/battery.c +++ b/openrtx/src/core/battery.c @@ -68,6 +68,12 @@ uint8_t battery_getCharge(uint16_t vbat) vb = vb / 1000; vb = (vb + 256) >> 8; + /* + * If the voltage is below minimum we return 0 to prevent an underflow in + * the following calculation + */ + if (vb < bat_v_min) return 0; + uint32_t diff = vb - bat_v_min; uint32_t range = bat_v_max - bat_v_min; uint32_t result = ((diff << 8) / range) * 100;