Calling the same function in two tasks of equal priority

I am using the INA219 I2C current sensor to monitor current and integrate it in one task and using it as feedback for a Mosfet gate in the main loop (using a DAC to lower vgs if the current is too high). I would like to be able to implement this feedback outside the integration loop for maximum accuracy of integration.
-What would happen if I continuously called the same function in both loops?
-Would putting a global variable for current acquisition be a better option ( one variable that is updated in one task so that it can be used by the main loop without calling the function twice) ?
I am new to RTOS and I apologize if this question has been asked before, I couldn’t find any similar ones.

There is no problem calling the same function from multiple threads, as long as the function was written to be thread-safe (like not using static variables for intermediary results).

As to reading a sensor, you likely want to be reading the sensor at a controlled fixed rate and passing that value to things that need the information.

1 Like

Unfortunately, I2C functions are not thread safe according to the ESP32 API reference (I cannot post a link since I am a new user).
Also, “passing that value to things that need the information” does this statement include what I said above about global variables? will there be a problem if both tasks try access the same global variable?

Multiple tasks can access a global variable. You may need to use a critical section if the access is not “Atomic”, so you can’t get part of the old value and part of the new if the update overlaps.

Your consumers of the data likely will want to know when the data is updated to process it.

Devices, like an I2C bus need to be protected by a Mutex or the like if you are going to access them from multiple threads, as the hardware naturally can’t do two different access cycles at the same time. I use a driver layer that includes that mutex so the application layer doesn’t need to worry about it normally.

1 Like