3.3 INA226模块驱动
#include "sys.h"
#include "myiic.h"
#define CFG_REG 0x00 //
#define SV_REG 0x01 //分流电压
#define BV_REG 0x02 //总线电压
#define PWR_REG 0x03 //电源功率
#define CUR_REG 0x04 //电流
#define CAL_REG 0x05 //校准,设定满量程范围以及电流和功率测数的
#define ONFF_REG 0x06 //屏蔽 使能 警报配置和转换准备就绪
#define AL_REG 0x07 //包含与所选警报功能相比较的限定值
#define INA226_GET_ADDR 0XFF /
//初始化INA226
void INA226_Init(void)
{
IIC_Init();
INA226_SendData(INA226_ADDR1,CFG_REG,0x8000); //重新启动
INA226_SendData(INA226_ADDR1,CFG_REG,0x484f); //设置转换时间204us,求平均值次数128,采样时间为204*128,设置模式为分流和总线连续模式
INA226_SendData(INA226_ADDR1,CAL_REG,CAL); //设置分辨率
//INA226_SendData(INA226_ADDR1,CAL_REG,0x0012);//设置分流电压转电流转换参数
INA226_Get_ID(INA226_ADDR1); //获取ina226的id
}
//设置寄存器指针
void INA226_SetRegPointer(u8 addr,u8 reg)
{
IIC_Start();
IIC_Send_Byte(addr);
IIC_Wait_Ack();
IIC_Send_Byte(reg);
IIC_Wait_Ack();
IIC_Stop();
}
//发送,写入数据
void INA226_SendData(u8 addr,u8 reg,u16 data)
{
u8 temp=0;
IIC_Start();
IIC_Send_Byte(addr);
IIC_Wait_Ack();
IIC_Send_Byte(reg);
IIC_Wait_Ack();
temp = (u8)(data>>8);
IIC_Send_Byte(temp);
IIC_Wait_Ack();
temp = (u8)(data&0x00FF);
IIC_Send_Byte(temp);
IIC_Wait_Ack();
IIC_Stop();
}
//读取数据
u16 INA226_ReadData(u8 addr)
{
u16 temp=0;
IIC_Start();
IIC_Send_Byte(addr+1);
IIC_Wait_Ack();
temp = IIC_Read_Byte(1);
temp<<=8;
temp |= IIC_Read_Byte(0);
IIC_Stop();
return temp;
}
//1mA/bit
u16 INA226_GetShunt_Current(u8 addr)
{
u16 temp=0;
INA226_SetRegPointer(addr,CUR_REG);
temp = INA226_ReadData(addr);
if(temp&0x8000) temp = ~(temp - 1);
return temp;
}
//获取id
void INA226_Get_ID(u8 addr)
{
u32 temp=0;
INA226_SetRegPointer(addr,INA226_GET_ADDR);
temp = INA226_ReadData(addr);
ina226_data.ina226_id = temp;
}
//获取校准值
u16 INA226_GET_CAL_REG(u8 addr)
{
u32 temp=0;
INA226_SetRegPointer(addr,CAL_REG);
temp = INA226_ReadData(addr);
return (u16)temp;
}
//1.25mV/bit
u16 INA226_GetVoltage(u8 addr)
{
u32 temp = 0;
INA226_SetRegPointer(addr,BV_REG);
temp = INA226_ReadData(addr);
return (u16)temp;
}
//2.5uV/bit
u16 INA226_GetShuntVoltage(u8 addr)
{
int16_t temp = 0;
INA226_SetRegPointer(addr,SV_REG);
temp = INA226_ReadData(addr);
if(temp&0x8000) temp = ~(temp - 1);
return (u16)temp;
}
//获取电压
void GetVoltage(float *Voltage)//mV
{
*Voltage = INA226_GetVoltage(INA226_ADDR1)*Voltage_LSB;
}
|