How tjoms99/xiao_sense_nrf52840_battery_lib works
Project Type and Purpose
• This is an embedded firmware library project for the XIAO BLE and XIAO BLE Sense (nRF52840) boards.
• It provides a Zephyr‐based battery management subsystem: reading battery voltage via ADC, computing percentage, controlling charge current, and firing callbacks for voltage sampling and charge‐state changes.
File Structure Analysis
• Top‐level CMakeLists.txt and prj.conf: standard Zephyr build and configuration.
• boards/ + dts/: Zephyr board overlay files and device-tree bindings define hardware peripherals (ADC channels, charger GPIO lines).
• src/battery/: the battery management library implementation (battery.c/.h).
• src/main.c: example application showing library usage.
Key README Insights
• Describes API functions (voltage read, percentage, charge‐mode set, sampling, callbacks).
• Mentions Zephyr RTOS, Nordic nRF Connect SDK, Adafruit UF2 bootloader, and serial logging.
Main Components
A. Hardware Layer
• LiPo battery (3.7 V)
• Battery charger IC (connected to battery and MCU via GPIO/I²C)
• nRF52840 MCU with onboard ADC and GPIO
• USB interface for UF2 bootloader / serial logging
B. Zephyr RTOS Layer
• Kernel (scheduling, threads, timers)
• Device Drivers
– ADC driver (reads battery voltage pin)
– GPIO or I2C driver (toggles charger mode pin or communicates with charger IC)
• Device Tree & Board Overlays (boards/*.overlay, dts/*.yaml)
C. Battery Management Library
• Initialization (battery_init)
• ADC sampling logic (one‐shot and periodic via Zephyr work queue or timer)
• Charge‐mode control (fast/slow)
• Callback registry (charging state, sample ready)
D. Application Layer (main.c example)
• Calls battery_init()
• Registers callbacks
• Starts periodic sampling
• Receives callbacks → handles logging or UI
Relationships & Data Flow
1. On boot → Zephyr kernel initializes hardware per device tree.
2. battery_init() sets up ADC channel and charger control GPIO via Zephyr APIs.
3. One‐shot or periodic sampling:
– Library schedules a Zephyr timer or work item.
– ADC driver reads battery voltage.
– Measured millivolt value flows back to library.
– Library computes percentage and invokes registered sample callbacks.
4. Charge mode changes (battery_set_fast_charge / slow): library calls GPIO or I2C driver → charger IC.
5. Charger IC state changes trigger an interrupt or polling → library invokes charging state callback.
6. main.c application callback handlers log to serial console (via Zephyr logging subsystem).
Architectural Patterns & Principles
• Layered architecture: Hardware → Zephyr RTOS → Device Drivers → Battery Library → Application.
• Inversion of Control via callbacks: library does work, application supplies handlers.
• Decoupling via Device Tree: hardware details abstracted away from C code.
• RTOS primitives (timers, work queues) for scheduling periodic sampling.