Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update BatteryLevel.ino to correct percentage remaining calculation #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion ESP32/BatteryLevel/BatteryLevel.ino
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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);
Expand Down