Files
JYF_STC15W4K_wireless_charge/Lib/ina226.c
2025-03-18 19:34:19 +08:00

49 lines
1.5 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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