Files
JYF_STC15W4K_wireless_charge/Lib/ina226.c

62 lines
1.5 KiB
C
Raw Normal View History

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
2025-03-19 17:25:17 +08:00
INA226_Init (float r_shunt, float max_current)
2025-03-18 22:49:46 +08:00
{
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);
2025-03-19 17:25:17 +08:00
IIC_WriteBytes (INA226_ADDR, reg, data_t, 2);
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];
2025-03-19 17:25:17 +08:00
IIC_ReadBytes (INA226_ADDR, reg, data_t, 2);
2025-03-18 22:49:46 +08:00
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-19 17:25:17 +08:00
// return raw * CurrentLSB; // 实测结果偏大
2025-03-18 19:34:19 +08:00
}