您好!
我编写了自己的小驱动程序、以便 MCU 可以与电池管理器通信。 但是、我可以读取温度和电压只是正常、但电流始终报告0mA。 为什么是这样?
下面是我使用的代码:
读取的两个字节代码:
/*
* reads two bytes from a register
*/
BAT_STATUS BAT_Read_Two_Bytes(BAT_StateHandle *hbat, uint8_t register_address,
uint16_t *pBytes) {
//we use the buffer to send the register we want to read
//the same buffer will be used later to store the answer
uint8_t buff[2] = { register_address, 0x00 };
//send which register we want to read
if (HAL_I2C_Master_Transmit(&hi2c2, hbat->address_i2c, &buff[0], 1,
BAT_TIMEOUT_LIMIT) != HAL_OK) {
return BAT_ERROR;
}
//now read it
// if (HAL_I2C_Master_Receive(&hi2c2, hbat->address_i2c, buff, 2,
// BAT_TIMEOUT_LIMIT) != HAL_OK) {
HAL_Delay(BAT_DELAY); //wait for the device to write the answer
if (HAL_I2C_Master_Receive(&hi2c2, hbat->address_i2c, buff, 2, BAT_TIMEOUT)
!= HAL_OK) {
return BAT_ERROR;
}
HAL_Delay(BAT_DELAY);
//fill in the result
if (pBytes) { //return ERROR if not there
*pBytes = (((uint16_t) buff[1]) << 8) + buff[0];
APP_LOG(TS_ON, VLEVEL_L, "reading two bytes buffer is [%d, %d]\n", buff[0], buff[1]);
} else {
return BAT_ERROR;
}
return BAT_OK;
}
以下是读取温度、电压和电流的函数:
/*
* the current flow in mA
*/
BAT_STATUS BAT_Get_Current(BAT_StateHandle *hbat, uint16_t *current) {
BAT_STATUS status;
status = BAT_Read_Two_Bytes(hbat, 0x0c, current);
APP_LOG(TS_ON, VLEVEL_L, "reading current %d \r\n", *current);
return status;
}
/*
* returns the voltage in mV
*/
BAT_STATUS BAT_Get_Voltage(BAT_StateHandle *hbat, uint16_t *voltage) {
return BAT_Read_Two_Bytes(hbat, BAT_REG_Voltage, voltage);
}
BAT_STATUS BAT_Get_Temperature(BAT_StateHandle *hbat, float *temperature) {
*temperature = -273.15f; //default is 0 Kelvin
uint16_t pBytes;
//read the register
BAT_STATUS status = BAT_Read_Two_Bytes(hbat, BAT_REG_Temperature, &pBytes);
if (status == BAT_OK) {
//interpret the value in pBytes as temperature
*temperature = (float) pBytes;
*temperature = (*temperature - 2731.5f) / 10.0f; //into Celcius
}
return status;
}
温度和电压工作正常。电流仅返回0。为什么? 他们的表现似乎大致相同。