使用stm32f103c8t6标准库通过PB10,PB11IIC2读取多个INA3221模块检测电流电压代码
时间: 2023-09-05 12:07:45 浏览: 165
以下是使用stm32f103c8t6标准库通过PB10,PB11IIC2读取多个INA3221模块检测电流电压的示例代码:
```c
#include "stm32f10x.h"
#include "stm32f10x_i2c.h"
#define INA3221_ADDR 0x80 // INA3221地址
void I2C_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_DeInit(I2C2);
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 100000;
I2C_Init(I2C2, &I2C_InitStructure);
I2C_Cmd(I2C2, ENABLE);
}
uint16_t I2C_ReadRegister(uint8_t addr, uint8_t reg)
{
uint16_t value = 0;
while (I2C_GetFlagStatus(I2C2, I2C_FLAG_BUSY));
I2C_GenerateSTART(I2C2, ENABLE);
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C2, INA3221_ADDR | I2C_Direction_Transmitter, ENABLE);
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(I2C2, reg);
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_GenerateSTART(I2C2, ENABLE);
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C2, INA3221_ADDR | I2C_Direction_Receiver, ENABLE);
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_RECEIVED));
value |= I2C_ReceiveData(I2C2) << 8;
while (!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_RECEIVED));
value |= I2C_ReceiveData(I2C2);
I2C_GenerateSTOP(I2C2, ENABLE);
return value;
}
void INA3221_GetVoltageAndCurrent(float *voltage, float *current)
{
uint16_t shunt_voltage = I2C_ReadRegister(INA3221_ADDR, 0x01); // 读取毫伏数值
uint16_t bus_voltage = I2C_ReadRegister(INA3221_ADDR, 0x02); // 读取总线电压值
uint16_t current_value = I2C_ReadRegister(INA3221_ADDR, 0x04); // 读取电流值
*voltage = ((float)bus_voltage / 32768.0) * 16.0; // 计算总线电压值,单位为V
*current = ((float)current_value / 32768.0) * 4.0; // 计算电流值,单位为A
}
int main(void)
{
float voltage, current;
I2C_Configuration();
while (1)
{
INA3221_GetVoltageAndCurrent(&voltage, ¤t);
}
}
```
在这个示例代码中,首先定义了INA3221的I2C地址为0x80。然后在`I2C_Configuration()`函数中初始化了I2C2,使用GPIOB的PB10和PB11引脚作为SCL和SDA。接下来定义了`I2C_ReadRegister()`函数用于读取INA3221的寄存器值,该函数通过I2C总线发送读取请求并接收返回数据。最后在`INA3221_GetVoltageAndCurrent()`函数中读取INA3221的总线电压值、电流值和毫伏数值,并计算出实际电压和电流值。
在`main()`函数中,我们使用`INA3221_GetVoltageAndCurrent()`函数读取INA3221的电压和电流值,并不断循环读取。
阅读全文