diff --git a/src/Battery.cpp b/src/Battery.cpp index 2f16709e..7c348d58 100644 --- a/src/Battery.cpp +++ b/src/Battery.cpp @@ -1,18 +1,26 @@ #include "Battery.h" -void BatteryPercentageRingBuffer::init(uint16_t v) { +void BatteryPercentageRingBuffer::init(uint8_t v) { for (size_t i = 0; i < MAX_SAMPLES; i++) { buf[i] = v; } sum = v * MAX_SAMPLES; prev_val = v; head = 0; + was_charging = true; } -void BatteryPercentageRingBuffer::update(uint16_t v) { +void BatteryPercentageRingBuffer::update(uint8_t v) { // Previous percentage is set > 100 only if buffer was constructed but not initialized yet if (prev_val > 100) { init(v); + was_charging = false; + } + + // Buffer was reintilialized with readout values while charging (can be too high values), reinit with new readout after charging + if (was_charging){ + init(v); + was_charging = false; } // Recalculate rolling sum @@ -25,10 +33,9 @@ void BatteryPercentageRingBuffer::update(uint16_t v) { if (head >= MAX_SAMPLES) head = 0; } -uint16_t BatteryPercentageRingBuffer::evaluate() { - // We 'round' (only works for pos numbers but oh well good enough for battery percentages) to an int - float avg = (sum / MAX_SAMPLES) + 0.5; - uint16_t new_val = (int)avg; +uint8_t BatteryPercentageRingBuffer::evaluate() { + + uint8_t new_val = (sum + MAX_SAMPLES / 2) / MAX_SAMPLES; // Battery percentage should not increase when not charging so we just cap it to be lower than the last value if (new_val < prev_val) { diff --git a/src/Battery.h b/src/Battery.h index 0baf56ae..97f9f294 100644 --- a/src/Battery.h +++ b/src/Battery.h @@ -8,14 +8,15 @@ static BatteryMonitor battery(BAT_GPIO0); struct BatteryPercentageRingBuffer { - static constexpr uint16_t MAX_SAMPLES = 10; + static constexpr uint8_t MAX_SAMPLES = 10; - uint16_t buf[MAX_SAMPLES]; - uint16_t head = 0; + uint8_t buf[MAX_SAMPLES]; + uint8_t head = 0; uint16_t sum = 0; - uint16_t prev_val = 161; + uint8_t prev_val = 161; + bool was_charging =false; - void init(uint16_t value); - void update(uint16_t value); - uint16_t evaluate(); + void init(uint8_t value); + void update(uint8_t value); + uint8_t evaluate(); };