From 6d1ef7e7b55350e7750ac4712ddec43947d2d1a3 Mon Sep 17 00:00:00 2001 From: itisishan Date: Mon, 19 Feb 2024 23:15:35 -0500 Subject: [PATCH] Update BatteryLevel.ino to correct percentage remaining calculation The original code reference calculation from Program the Internet of Things with Swift for iOS (https://books.google.com/books?id=UqR8DwAAQBAJ&lpg=PA187&dq=lipoly%20battery%20indicator%20huzzah32&pg=PA187#v=onepage&q=lipoly%20battery%20indicator%20huzzah32&f=false). However this calculation does not account for the fact that 0% of a LiPo's SOC is at 3.2V and not 0V. Updated code with new calculation and some additional notes. --- ESP32/BatteryLevel/BatteryLevel.ino | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ESP32/BatteryLevel/BatteryLevel.ino b/ESP32/BatteryLevel/BatteryLevel.ino index 3abf937..dd5ab23 100644 --- a/ESP32/BatteryLevel/BatteryLevel.ino +++ b/ESP32/BatteryLevel/BatteryLevel.ino @@ -15,6 +15,7 @@ */ const int MAX_ANALOG_VAL = 4095; const float MAX_BATTERY_VOLTAGE = 4.2; // Max LiPoly voltage of a 3.7 battery is 4.2 +const float MIN_BATTERY_VOLTAGE = 3.2; // The system will brown out around 3.2V (undervoltage protection circuitry kicks in). Note that Li-ion chemistry carries very limited usuable energy under 3.2V and will damage the battery with complete depletion. void setup() { // put your setup code here, to run once: @@ -33,7 +34,9 @@ void loop() { // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html#adc-calibration // See also: https://bit.ly/2zFzfMT float voltageLevel = (rawValue / 4095.0) * 2 * 1.1 * 3.3; // calculate voltage level - float batteryFraction = voltageLevel / MAX_BATTERY_VOLTAGE; + float batteryFraction = (voltageLevel - MIN_BATTERY_VOLTAGE) / (MAX_BATTERY_VOLTAGE - MIN_BATTERY_VOLTAGE); + // Battery "percentage remaining" is with reference to 100% being a fully charged battery and 0% being when the system will shutdown. + // Note that this is a gross approximation and modelling remaing battery state of charage (SOC) is a much more complicated task done by battery fuel gauge ICs (see https://www.richtek.com/m/~/media/AN%20PDF/AN024_EN.pdf) Serial.println((String)"Raw:" + rawValue + " Voltage:" + voltageLevel + "V Percent: " + (batteryFraction * 100) + "%"); delay(1000);