2026-01-14 11:33 AM - last edited on 2026-01-15 1:21 AM by Andrew Neil
Hi there !
I use thi function and work perfectly . But if i try to read the HAL_StatusTypeDef i don't understand why return HAL_OK even if i wrote a wrong address why ????
if i use void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) this work with i wrote a wrong address
please some one can tell me why ?
Thank you
Sergio
Solved! Go to Solution.
2026-01-15 1:16 AM - edited 2026-01-15 1:19 AM
@SGian.1 wrote:i don't understand why return HAL_OK even if i wrote a wrong address
What do you mean by "wrong address" here - I2C Slave address, or some other (memory) address?
If it's the I2C Slave address, then the code has no way to tell in advance what slave addresses are present in your external hardware - so it can't tell in advance if the address is "valid" or not.
PS:
You can use HAL_I2C_IsDeviceReady() to check if a particular Slave address device is present & responding on the bus.
2026-01-14 1:35 PM - last edited on 2026-01-15 1:13 AM by Andrew Neil
You can look at the HAL source code to see what error conditions the function checks for.
Null pointer, 0 length -> HAL_ERROR
I2C in use already -> HAL_BUSY
Other erroneous possibilities are not checked for.
There are some HAL functions that always return HAL_OK.
if (hi2c->State == HAL_I2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM;
return HAL_ERROR;
}
if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}Edited to apply source code formatting - please see How to insert source code for future reference.
2026-01-14 9:24 PM
Because this function is asynchronous. When it returns, the target device has not responded (or not) yet. So the error callback is the only way to know the outcome.
2026-01-15 1:16 AM - edited 2026-01-15 1:19 AM
@SGian.1 wrote:i don't understand why return HAL_OK even if i wrote a wrong address
What do you mean by "wrong address" here - I2C Slave address, or some other (memory) address?
If it's the I2C Slave address, then the code has no way to tell in advance what slave addresses are present in your external hardware - so it can't tell in advance if the address is "valid" or not.
PS:
You can use HAL_I2C_IsDeviceReady() to check if a particular Slave address device is present & responding on the bus.
2026-01-15 2:00 AM
I mean i try to send another address just check if i receive HAL_ERROR or somethingh else.
Thank you all you guys for the help
2026-01-15 2:31 AM
So as @Pavel A. and I both said, the software cannot know in advance whether an address is or is not active on the external bus: it can only tell that by receiving the ACK or NACK - and that only becomes available in the callback.
If you want to know immediately, you have to use the synchronous (blocking) API.