switch to uint8 and fix faulty charging readouts being displayed

This commit is contained in:
Dave ID 2026-02-04 11:08:29 +01:00
parent a3dca29b43
commit ee75345684
2 changed files with 21 additions and 13 deletions

View File

@ -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) {

View File

@ -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();
};