main
Drew Owens Publish Microgoose Rev A full-stack hardware, CAD, datasheet, and 7-stage RL stack e843249
/*
 * ina226.h
 * TI INA226AIDGST (U3, I2C1 0x40) high-side voltage, current, and power monitor
 * across R20 Bourns CSS2H-2512R-L300F (0.30 mOhm / 0.0003 Ohm, 1%, CAL = 17067 for
 * 1 mA/LSB, 32.768 A signed current register range) + PA0 VBAT_ADC helper.
 */

#ifndef MICROGOOSE_INA226_H
#define MICROGOOSE_INA226_H

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "bmi270_min.h"

/* INA226 Register Addresses */
#define INA226_REG_CONFIG               0x00U
#define INA226_REG_SHUNT_VOLTAGE        0x01U  /* 2.5 uV/LSB signed (+/-81.92 mV FS) */
#define INA226_REG_BUS_VOLTAGE          0x02U  /* 1.25 mV/LSB unsigned */
#define INA226_REG_POWER                0x03U  /* 25 * Current_LSB unsigned */
#define INA226_REG_CURRENT              0x04U  /* 1.0 mA/LSB signed when CAL=17067 @ 0.30 mOhm */
#define INA226_REG_CALIBRATION          0x05U
#define INA226_REG_MASK_ENABLE          0x06U
#define INA226_REG_ALERT_LIMIT          0x07U
#define INA226_REG_MANUFACTURER_ID      0xFEU  /* 0x5449 ("TI") */
#define INA226_REG_DIE_ID               0xFFU  /* 0x2260 */

#define INA226_MFG_ID_EXPECTED          0x5449U
#define INA226_DIE_ID_EXPECTED          0x2260U

/*
 * CONFIG: 16-sample averaging (AVG=010), 1.1 ms VBUS + 1.1 ms VSHUNT conversion,
 * continuous shunt and bus mode -> 0x4527 (~28 Hz averaged update, zero aliasing).
 */
#define INA226_CONFIG_AVG16_CONT        0x4527U

typedef struct {
    uint8_t         i2c_addr;
    uint32_t        shunt_uohm;
    uint16_t        cal_reg;
    mg_i2c_read_fn  i2c_read;
    mg_i2c_write_fn i2c_write;
    void           *bus_ctx;
    bool            initialized;
} ina226_dev_t;

typedef struct {
    int32_t  shunt_uv;
    uint16_t bus_mv;
    int16_t  current_ma;
    uint32_t power_mw;
} ina226_reading_t;

/*
 * Compute INA226 CALIBRATION register for Current_LSB = 1 mA (0.001 A):
 *   CAL = round(0.00512 / (0.001 * R_shunt_ohm)) = round(5,120,000 / shunt_uohm).
 * For R20 Bourns CSS2H-2512R-L300F (0.30 mOhm = 300 uOhm): CAL = 17067 (0x42AB).
 */
uint16_t ina226_compute_cal_1ma_lsb_uohm(uint32_t shunt_uohm);

/* Pure fixed-point register conversions (zero floating-point required) */
int32_t  ina226_shunt_raw_to_uv(int16_t raw_shunt);
uint16_t ina226_bus_raw_to_mv(uint16_t raw_bus);
int16_t  ina226_shunt_and_cal_to_ma(int16_t raw_shunt, uint16_t cal_reg);
uint32_t ina226_power_raw_to_mw(uint16_t raw_power);

/* PA0 (U4.8, ADC1_IN1) 12-bit VBAT_ADC conversion (R11=100k / R12=33k -> ratio 133 / 33) */
uint16_t mg_adc_vbat_div_to_mv(uint16_t adc_counts_12b);

/* I2C device initialization and register polling */
bool ina226_init(
    ina226_dev_t *dev,
    uint8_t i2c_addr,
    uint32_t shunt_uohm,
    mg_i2c_read_fn read_fn,
    mg_i2c_write_fn write_fn,
    void *bus_ctx
);

bool ina226_read(ina226_dev_t *dev, ina226_reading_t *out);

#endif /* MICROGOOSE_INA226_H */