HAL_I2C_Mem_Read函数实现
时间: 2023-07-24 12:05:58 浏览: 270
HAL_I2C_Mem_Read 函数是基于 HAL 库和 STM32 的硬件 I2C 接口实现的,用于从 I2C 设备的指定寄存器中读取数据。下面是 HAL_I2C_Mem_Read 函数的具体实现:
```
HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
HAL_StatusTypeDef status = HAL_OK;
status = HAL_I2C_Mem_Read_IT(hi2c, DevAddress, MemAddress, MemAddSize, pData, Size);
if (status != HAL_OK)
{
return status;
}
status = HAL_I2C_WaitReady(hi2c, Timeout);
if (status != HAL_OK)
{
return status;
}
return HAL_OK;
}
HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
HAL_StatusTypeDef status = HAL_OK;
if (hi2c->State == HAL_I2C_STATE_READY)
{
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferSize = Size;
hi2c->MemAddress = MemAddress;
hi2c->MemAddSize = MemAddSize;
hi2c->DevAddress = DevAddress;
hi2c->XferDirection = I2C_DIRECTION_RECEIVE;
status = I2C_RequestMemoryRead(hi2c);
if (status != HAL_OK)
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->ErrorCode |= HAL_I2C_ERROR_REQUEST;
}
else
{
hi2c->State = HAL_I2C_STATE_BUSY_RX;
}
}
else
{
status = HAL_BUSY;
}
return status;
}
HAL_StatusTypeDef HAL_I2C_WaitReady(I2C_HandleTypeDef *hi2c, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
while (hi2c->State != HAL_I2C_STATE_READY)
{
if ((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick() - tickstart) >= Timeout))
{
hi2c->State = HAL_I2C_STATE_READY;
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
```
HAL_I2C_Mem_Read 函数首先调用了 HAL_I2C_Mem_Read_IT 函数,该函数负责向 I2C 设备发出读取指定寄存器的请求,然后等待 I2C 设备的响应。如果读取成功,函数会返回 HAL_OK;否则,函数会返回错误码。如果读取操作未完成,HAL_I2C_Mem_Read 函数将等待 I2C 设备的响应,直到超时或者读取完成为止。
HAL_I2C_Mem_Read_IT 函数主要负责设置 I2C 设备的读取参数,然后向 I2C 设备发出读取指定寄存器的请求。如果读取请求成功,函数会返回 HAL_OK;否则,函数会返回错误码。
HAL_I2C_WaitReady 函数用于等待 I2C 设备的响应。如果 I2C 设备未响应,函数将返回超时错误码 HAL_TIMEOUT;如果 I2C 设备的响应已经完成,函数将返回 HAL_OK。
阅读全文