Skip to content
Merged
Show file tree
Hide file tree
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
28 changes: 13 additions & 15 deletions main/bat.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ static adc_cali_handle_t adc1_cali_handle = NULL;
static uint32_t batMv = 27600;

// We try to measure every 100ms, so 100 points gives us 10 seconds history.
static uint8_t history[100];
static size_t historyIndex = 0;
static size_t historySize = 0;
static uint32_t history;
static uint8_t batPercentage;

// static size_t historyIndex = 0;
// static size_t historySize = 0;

static void adc_calibration_init(adc_unit_t unit, adc_atten_t atten) {
esp_err_t ret = ESP_FAIL;
Expand Down Expand Up @@ -130,29 +132,25 @@ static uint8_t batMvToPercentage(uint32_t batMv) {

void measureBat() {
batMv = measureBatMv();
history[historyIndex] = batMvToPercentage(batMv);
historyIndex = (historyIndex + 1) % sizeof(history);
if(historySize < sizeof(history)) {
historySize++;
}

history += batMv;
uint32_t avg = history >> 7;
history -= avg;

batPercentage = batMvToPercentage(avg);
}

uint32_t getBatMv() {
return batMv;
}

uint8_t getBatPercentage() {
if(historySize == 0) {
if(batPercentage == 0) {
// Use a fake value of 50% when we don't have ADC.
return 50;
}

uint32_t historyTotal = 0;
for(int index = 0; index < historySize; index++) {
historyTotal += history[index];
}

return historyTotal / historySize;
return batPercentage;
}

void adc_teardown() {
Expand Down
1 change: 1 addition & 0 deletions sdkconfig.supermini
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ CONFIG_ION_RELAY_PIN_INVERTED=n
CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160=y

CONFIG_ION_ADC=y

# ADC channel 1 is pin 2
CONFIG_ION_ADC_CHAN=2

Expand Down