3S Li-ion BMS / INA219 driver

A 3S Li-ion battery management system on ESP32, with a register-level INA219 driver on ESP-IDF and FreeRTOS tasks.

Status
Prototype
Stack
C++ · ESP-IDF · FreeRTOS · CMake · I2C · INA219
Source
github.com/wcnrny/ina219_Library

A 3S Li-ion battery management system built around an ESP32 and INA219 power monitors.

  • The INA219 driver is an ESP-IDF component in C++. It uses the ESP-IDF I2C master API for the bus and handles the INA219 registers (calibration, bus voltage, current) as the Texas Instruments datasheet describes.
  • FreeRTOS tasks separate telemetry logging from the safety cutoff. The fault-detection task runs at the highest priority, pinned to core 1.
  • If a cell drops below the safe threshold, the ESP32 pulls the MOSFET gate pins low through GPIOs.

The INA219 library is on GitHub. The BMS firmware is still in development.

The background is in the note Owning the Telemetry: Why I Built a Custom ESP32 BMS from Scratch.

Driver code

From wcnrny/ina219_Library, include/ina219_library.h:

#pragma once
#include "driver/i2c_master.h"
#include <cstdint>

class INA219
{
private:
    i2c_master_dev_handle_t _dev_handle;
    uint8_t _dev_addr;

    static constexpr uint8_t REG_CONFIG = 0x00;
    static constexpr uint8_t REG_CURRENT = 0x04;
    static constexpr uint8_t REG_CALIBRATION = 0x05;
    static constexpr uint8_t REG_BUS_VOLTAGE = 0x02;

public:
    INA219(i2c_master_bus_handle_t bus_handle,
           uint8_t dev_addr = CONFIG_INA219_DEV_ADDR);

    esp_err_t calibrate(uint16_t cal_value = CONFIG_INA219_CALIBRATION_VALUE);

    esp_err_t readCurrent_mA(float *out_current);
    ~INA219();

    esp_err_t readBusVoltage_V(float *out_voltage);
};

ina219_library.cpp, calibration and current reading:

esp_err_t INA219::calibrate(uint16_t cal_value)
{
    uint8_t payload[3];
    payload[0] = REG_CALIBRATION;
    payload[1] = static_cast<uint8_t>(cal_value >> 8);
    payload[2] = static_cast<uint8_t>(cal_value & 0xFF);

    return i2c_master_transmit(_dev_handle, payload, sizeof(payload), 100);
};

esp_err_t INA219::readCurrent_mA(float *out_current)
{
    uint8_t rx_data[2];
    esp_err_t err = i2c_master_transmit_receive(_dev_handle, &REG_CURRENT, 1, rx_data, sizeof(rx_data), 100);

    if (err != ESP_OK)
    {
        return err;
    }

    int16_t raw_current = (rx_data[0] << 8) | rx_data[1];

    *out_current = (float)raw_current * 0.01f;
    return ESP_OK;
};

Contact

Open to internships and working-student roles from Summer 2027. Email is the fastest way to reach me.

contact@wcnrny.tr