Fix the XIAO battery reading: busy-wait for the divider to settle

At CONFIG_FREERTOS_HZ=100 pdMS_TO_TICKS(5) is zero ticks, so the switched divider
had not settled when the ADC was read and battery_mv came out as 0. Wait 5 ms with
esp_rom_delay_us and configure GPIO26 with gpio_config. The XIAO on COM10 now
reads 4153-4156 mV on a charging cell.
This commit is contained in:
Ashin Walpola
2026-11-11 14:17:38 +01:00
parent 6f99154b23
commit c78b66341b
3 changed files with 16 additions and 3 deletions
+5
View File
@@ -52,6 +52,11 @@ custom PCB; pick it in `menuconfig -> micrOBU firmware -> Board`.
protection board, so `battery_policy.hpp` (smoothing, warning hysteresis, shutdown) deep-sleeps the
board below 3.30 V for 30 s when no phone is on USB, re-checks every 5 min, and runs again from
3.60 V. Thresholds: `menuconfig -> micrOBU firmware`.
- **Battery reading fix** (`battery_monitor.cpp`, found on the XIAO 2026-11-11: `battery_mv` was 0). At
`CONFIG_FREERTOS_HZ=100` `vTaskDelay(pdMS_TO_TICKS(5))` is zero ticks, so the switched divider never
settled before the ADC read it and every sample fell below the 2.5 V validity floor. It is now a 5 ms
busy wait, and GPIO26 is set up with `gpio_config`. Worth telling Niklas Dathe: his mainboard-v5 has no
switched divider and is not affected. With the fix the XIAO reads 4153-4156 mV on a charging cell.
- **Serial link**: no write attempt while no USB host is connected; `last_frame_ms()` tells the battery
guard whether a phone is powering the board.
- **Partition table**: 80 KB NVS (Niklas Dathe's 24 KB filled up and BLE bonds stopped persisting),
+10 -2
View File
@@ -5,6 +5,7 @@
#include <freertos/task.h>
#include <esp_log.h>
#include <esp_sleep.h>
#include <esp_rom_sys.h>
namespace microbu {
BatteryMonitor::BatteryMonitor() {
@@ -33,7 +34,11 @@ BatteryMonitor::BatteryMonitor() {
return;
}
#if CONFIG_MICROBU_XIAO_C5_BATTERY
gpio_set_direction(GPIO_NUM_26, GPIO_MODE_OUTPUT);
// MicrOBU: gpio_config, not gpio_set_direction alone, so the pad is certainly a plain GPIO output.
gpio_config_t enable = {};
enable.pin_bit_mask = 1ULL << 26;
enable.mode = GPIO_MODE_OUTPUT;
gpio_config(&enable);
gpio_set_level(GPIO_NUM_26, 0);
#endif
#endif
@@ -54,7 +59,10 @@ std::uint16_t BatteryMonitor::sample_millivolts() {
#if CONFIG_MICROBU_XIAO_C5_BATTERY
gpio_set_level(GPIO_NUM_26, 1);
#endif
vTaskDelay(pdMS_TO_TICKS(5)); // settle the switched 100k/100k divider
// MicrOBU: a busy wait. At CONFIG_FREERTOS_HZ=100 pdMS_TO_TICKS(5) is 0 ticks, so vTaskDelay returned at
// once, the switched divider had not settled, and every reading came out below the 2.5 V validity floor
// (battery_mv 0 on the XIAO, 2026-11-11).
esp_rom_delay_us(5000); // settle the switched 100k/100k divider
int sum = 0;
bool valid = true;
for (unsigned i = 0; i < 16; ++i) {