Skip to main content
Graduate II
January 25, 2024
Solved

Is I2C HAL library for F4 series thread safe?

  • January 25, 2024
  • 6 replies
  • 2244 views

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.
    This topic has been closed for replies.
    Best answer by Tesla DeLorean

    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.

    6 replies

    Graduate II
    January 25, 2024

    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.

    HDaji.1Author
    Graduate II
    January 25, 2024

    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?
    Super User
    January 25, 2024

    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.

    HDaji.1Author
    Graduate II
    January 26, 2024

    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 

    Super User
    January 26, 2024

    >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.1Author
    Graduate II
    January 30, 2024

    We are not bug, but bug creator.:beaming_face_with_smiling_eyes: