cancel
Showing results for 
Search instead for 
Did you mean: 

Is I2C HAL library for F4 series thread safe?

HDaji.1
Senior

In my project, my MCU (F411) uses I2C HAL API routinely to read from a sensor device.

When some event happens, my interrupt handler will use I2C API to read from different register from that device; so my question is:

  • Is HAL API thread safe? Although I don't use RTOS, there is possibility that my code may try to use I2C interface at the same time.
1 ACCEPTED SOLUTION

Accepted Solutions

Probably not in the way you need it to be.

If interacting from multiple interrupts and callbacks you probably want to serialize or queue operations you want to perform. ie you complete one slave command or operation and then sequence to the next.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

View solution in original post

6 REPLIES 6

Probably not in the way you need it to be.

If interacting from multiple interrupts and callbacks you probably want to serialize or queue operations you want to perform. ie you complete one slave command or operation and then sequence to the next.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
HDaji.1
Senior

Hi @Tesla DeLorean 

Thx for your advice.

I am curious to know:

  • If there is one main loop, in which MCU periodically calls I2C HAL API to get data from the sensor through I2C; and in the interrupt handler function, MCU calls I2C API to talk to the same sensor as well. If I don't set a flag to indicate I2C being busy or not. How would the compiler schedule the two API call instances?
TDK
Guru

The compiler doesn't schedule anything, it'll call what you told it to call. Calling I2C from the main thread and the IRQ is not advisable. If the main thread is in the middle of an I2C call, the IRQ call will fail (at best) or corrupt what was going on (at worst). There is a locking mechanism but it is not robust.

If you feel a post has answered your question, please click "Accept as Solution".
HDaji.1
Senior

If it's not the compiler, then it's the MCU itself, isn't it?

I imagine that MCU is doing I2C operation, if IRQ occurs, it pauses I2C in the middle of somewhere, and responds. If in the IRQ there is another I2C call, it leads to big trouble: not only new I2C call fails, but also the existing I2C is disrupted.

I guess that's why it is advised that IRQ function is as slim as possible.

Thx. @TDK 

Pavel A.
Evangelist III

>If it's not the compiler, then it's the MCU itself, isn't it?

It's the programmer. The person who designs the code. A bug between the chair and the keyboard, as they used to call this ~ 30 years ago))

 

HDaji.1
Senior

We are not bug, but bug creator.😁