From fccf95c125e11032574b77c2cfcdfeaca4356485 Mon Sep 17 00:00:00 2001 From: thiswillbeyourgithub Date: Wed, 16 Mar 2022 15:55:27 +0100 Subject: [PATCH] fix: smoothen battery voltage Signed-off-by: thiswillbeyourgithub --- wasp/drivers/battery.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/wasp/drivers/battery.py b/wasp/drivers/battery.py index e866920..e339fdc 100644 --- a/wasp/drivers/battery.py +++ b/wasp/drivers/battery.py @@ -26,6 +26,7 @@ class Battery(object): self._battery = ADC(battery) self._charging = charging self._power = power + self._cache = set() @micropython.native def charging(self): @@ -33,7 +34,7 @@ class Battery(object): :returns: True if the battery is charging, False otherwise. """ - return self._charging.value() + return self._charging.value() def power(self): """Check whether the device has external power. @@ -50,10 +51,21 @@ class Battery(object): Assumes a 50/50 voltage divider and a 3.3v power supply + The last values is kept in a cache and only the minium cached value is + shown to the user, this is to avoid the battery level + going up and down because of the lack of precision of the mv. + Note that this will underestimate battery level. + :returns: Battery voltage, in millivolts. """ raw = self._battery.read_u16() - return (2 * 3300 * raw) // 65535 + mv = (2 * 3300 * raw) // 65535 + + if mv not in self._cache: + self._cache.add(mv) + while len(self._cache) > 2: + self._cache.remove(max(self._cache)) + return min(self._cache) def level(self): """Estimate the battery level. @@ -61,15 +73,12 @@ class Battery(object): The current the estimation approach is extremely simple. It is assumes the discharge from 4v to 3.5v is roughly linear and 4v is 100% and that 3.5v is 5%. Below 3.5v the voltage will start to drop pretty - sharply to we will drop from 5% to 0% pretty fast... but we'll + sharply so we will drop from 5% to 0% pretty fast... but we'll live with that for now. :returns: Estimate battery level in percent. """ mv = self.voltage_mv() level = ((19 * mv) // 100) - 660 - if level > 100: - return 100 - if level < 0: - return 0 + level = min(100, max(0, level)) return level