This is a generic question about mutexes. I am using an I2C library that starts a transmission with an API call, and signals completion with a callback called from an ISR.
Now, I would use mutex to allow several tasks to share the use of the I2C library, with the calling task taking the mutex before starting the transmission, and the callback giving the mutex. But the mutex give/take functions cannot be called from ISR context. I am using a semaphore but I am getting hard faults that I can’t track down.
Here is the code:
static SemaphoreHandle_t l_i2c_mutex;
static void i2cInitMutex(void) {
l_i2c_mutex = xSemaphoreCreateBinary();
xSemaphoreGive(l_i2c_mutex);
}
static void i2cAcquireI2cMutex(void) { // Called before starting I2C transmission.
xSemaphoreTake(l_i2c_mutex, portMAX_DELAY);
}
static void i2cReleaseI2cMutexFromIsr(void) { // Called by ISR when transmission complete.
xSemaphoreGiveFromISR(l_i2c_mutex, NULL);
}
I think you problem is that you has NULL as param in the
xSemaphoreGiveFromISR(l_i2c_mutex, NULL) function…
In the ISR yo need to supply the pxHigherPriorityTaskWoken parameter
That should not cause it to hard fault, but it will mean that a switch
to a task that was waiting for the mutex being returned will not occur
until the next tick interrupt - or until the task that is currently
running yields (because it blocked or manually called task Yield).
From the original post:
But the mutex
give/take functions cannot be called from ISR context.
Sorry it took so long. FreeRTOS V8.0.1 on LPC1549 using LPCExpresso IDE.
I have now confirmed that my use of mutexes is not the problem, but I would appresciate an inswer to a related question.
I have seen code where a mutex lock is created with a call to xSemaphoreCreateMutex(), but the lock is given/taken with calls to xSemaphoreGiveFrom ISR() & xSemaphoreTake(). Is this legal?
How that works depends on the version of FreeRTOS you are using - and
version 8.1.2 made some improvements in that area to make it easier to
integrate with third party software - but yes it is legal.