2025-03-18 19:34:19 +08:00
|
|
|
|
#include "ina226.h"
|
|
|
|
|
|
2025-03-18 22:49:46 +08:00
|
|
|
|
static float CurrentLSB; // 电流分辨率
|
2025-03-18 19:34:19 +08:00
|
|
|
|
|
2025-03-18 22:49:46 +08:00
|
|
|
|
void
|
|
|
|
|
INA226_Init (uint16_t r_shunt, float max_current)
|
|
|
|
|
{
|
|
|
|
|
uint16_t cal = 0;
|
2025-03-18 19:34:19 +08:00
|
|
|
|
|
2025-03-18 22:49:46 +08:00
|
|
|
|
// 1. 计算校准参数
|
|
|
|
|
CurrentLSB = max_current / 32768.0f; // 公式来源
|
|
|
|
|
cal = (uint16_t)(0.00512f / (CurrentLSB * r_shunt)); // 校准公式
|
2025-03-18 19:34:19 +08:00
|
|
|
|
|
2025-03-18 22:49:46 +08:00
|
|
|
|
// 2. 配置寄存器设置(平均64次,转换时间8.244ms)
|
|
|
|
|
INA226_WriteReg (CONFIG_REG, 0x45FF); // 配置值参考
|
2025-03-18 19:34:19 +08:00
|
|
|
|
|
2025-03-18 22:49:46 +08:00
|
|
|
|
// 3. 写入校准寄存器
|
|
|
|
|
INA226_WriteReg (CAL_REG, cal); // 校准配置方法
|
2025-03-18 19:34:19 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 寄存器写入函数
|
2025-03-18 22:49:46 +08:00
|
|
|
|
void
|
|
|
|
|
INA226_WriteReg (uint8_t reg, uint16_t value)
|
|
|
|
|
{
|
|
|
|
|
uint8_t data_t[2];
|
|
|
|
|
data_t[0] = (uint8_t)(value >> 8);
|
|
|
|
|
data_t[1] = (uint8_t)(value & 0xFF);
|
|
|
|
|
IIC_WriteBytes (INA226_ADDR, reg, data_t, 2); // 需适配您的I2C驱动
|
2025-03-18 19:34:19 +08:00
|
|
|
|
}
|
|
|
|
|
// 寄存器读取函数
|
2025-03-18 22:49:46 +08:00
|
|
|
|
uint16_t
|
|
|
|
|
INA226_ReadReg (uint8_t reg)
|
|
|
|
|
{
|
|
|
|
|
uint8_t data_t[2];
|
|
|
|
|
IIC_ReadBytes (INA226_ADDR, reg, data_t, 2); // 需适配您的I2C驱动
|
|
|
|
|
return (data_t[0] << 8) | data_t[1];
|
2025-03-18 19:34:19 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 电压读取(单位:V)
|
2025-03-18 22:49:46 +08:00
|
|
|
|
float
|
|
|
|
|
INA226_ReadBusVoltage (void)
|
|
|
|
|
{
|
|
|
|
|
int16_t raw = (int16_t)INA226_ReadReg (BUS_V_REG);
|
|
|
|
|
return raw * 0.00125f; // LSB=1.25mV
|
2025-03-18 19:34:19 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 电流读取(单位:A)
|
2025-03-18 22:49:46 +08:00
|
|
|
|
float
|
|
|
|
|
INA226_ReadCurrent (void)
|
|
|
|
|
{
|
|
|
|
|
int16_t raw = (int16_t)INA226_ReadReg (CURRENT_REG);
|
|
|
|
|
return raw * CurrentLSB; // 应用校准参数
|
2025-03-18 19:34:19 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 功率读取(单位:W)
|
2025-03-18 22:49:46 +08:00
|
|
|
|
float
|
|
|
|
|
INA226_ReadPower (void)
|
|
|
|
|
{
|
|
|
|
|
int16_t raw = (int16_t)INA226_ReadReg (POWER_REG);
|
|
|
|
|
return raw * 25 * CurrentLSB; // P=25×CurrentLSB×raw
|
2025-03-18 19:34:19 +08:00
|
|
|
|
}
|