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.
This commit is contained in:
marco 2023-09-22 19:01:19 +02:00 committed by Silvano Seva
parent e2ab831c27
commit 0126efe429
1 changed files with 6 additions and 0 deletions

View File

@ -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;