From 8f22c2e8525120b51c3c967c8467d5a14b30f1fb Mon Sep 17 00:00:00 2001 From: Kenneth Barbour Date: Tue, 16 Jun 2020 20:32:41 -0400 Subject: [PATCH] added a rough mapping of voltage to percent --- src/battery.h | 16 ++++++++++++++++ src/web.cpp | 5 +++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/battery.h b/src/battery.h index 771c90c..916f7ef 100644 --- a/src/battery.h +++ b/src/battery.h @@ -6,6 +6,8 @@ const int BATT_IN_PIN = A0; const int BATTERY_CHECK_INTERVAL = 5000; +const double BATTERY_PERCENT_MAP[] = {3.2, 3.6, 3.65, 3.7, 3.75, 3.85, 4.9, 4.0, 4.1, 4.15, 4.2}; + typedef struct battery_info_t { uint last_raw = 0; @@ -21,6 +23,20 @@ float battery_get_voltage() return (float) Battery.last_raw * .00042; } +unsigned int battery_get_percent() +{ + float v = battery_get_voltage(); + int i = 0; // find the index of the first map element higher than v + if (v >= BATTERY_PERCENT_MAP[10]) return 100; + while (BATTERY_PERCENT_MAP[i] <= v) i++; + if (i == 0) return 0; + + float a = v - BATTERY_PERCENT_MAP[i-1]; + float b = BATTERY_PERCENT_MAP[i] - BATTERY_PERCENT_MAP[i-1]; + float c = a / b * 10; + return (i-1) * 10 + c; +} + void uweather_handle_battery() { unsigned long now = millis(); diff --git a/src/web.cpp b/src/web.cpp index 43b088c..58db67d 100644 --- a/src/web.cpp +++ b/src/web.cpp @@ -88,12 +88,13 @@ void handle_weather_current(HttpRequest& req, HttpResponse& res) dtostrf(battery_get_voltage(), 2, 1, buff[3]); Serial.printf("temp= %s, pres= %s, hum=%s\r\n", buff[0], buff[1], buff[2]); res.headers.set("Content-Type", "application/json"); - content.printf("{\"time\": null, \"temperature\": %s, \"pressure\": %s, \"humidity\": %s, \"battery\": { \"voltage\": %s, \"is_charging\": %s}}", + content.printf("{\"time\": null, \"temperature\": %s, \"pressure\": %s, \"humidity\": %s, \"battery\": { \"voltage\": %s, \"is_charging\": %s, \"percent\": %d}}", buff[0], buff[1], buff[2], buff[3], - (Battery.is_charging ? "true":"false") + (Battery.is_charging ? "true":"false"), + battery_get_percent() ); }