Mutex – Error when trying to Give the mutex after Take

Hi, I was looking around the forum but didn’t find the same problem. Maybe I’m overseeing something, in fact I could use some help! I want to protect a shared resource (SPI) using a mutex. The main project is based on STM Cube MX (STM32L4 MCU). I always control the return values of the xSemaphore… functions. So init works also fine. When I use the Mutex in a test case (one and only Task “defaultTask”) it works without errors: ~~~ /* StartDefaultTask function / void StartDefaultTask(void const * argument) { osDelay(500); / USER CODE BEGIN 5 / / Infinite loop */ for(;;) { if(xSemaphoreTake(MutexHandle) != pdTRUE) { Error_Handler(); } osDelay(1000); if(xSemaphoreGive(MutexHandle) != pdTRUE) { Error_Handler(); } osDelay(1000);
}
/* USER CODE END 5 */ } ~~~ In my user code, different tasks need the SPI resource during their initialisation, so before the infinite loop in the tasks. The calls are similar as in the example above, instead of a delay I use the SPI to read/write stuff. When I run the code, I’m running into errors when trying to give the Mutex. So the task was able to take it, but is unable to give after that. What could be the reason for that? I don’t get it… What could i do to investigate deeper into that? I tried to use xSemaphoreGetMutexHolder between the Take and Give but it throws me a Compile Error ” undefined reference to ‘xQueueGetMutexHolder’ ” (although configUSE_MUTEXES is set to 1 in FreeRTOSConfig.h) Could I try the whole implementation with a binary semaphore instead? Best regards, Alex

Mutex – Error when trying to Give the mutex after Take

One issue I see is that you are missing a parameter to xSemaphoreTake, it needs a second parameter to specify how long it is allowed to wait. If the unprovided parameter happens to be 0, then the take will return immediately. Second, you code looks like it could go on and assume it has the mutex if the take fails (assuming Error_Handler just logs an error and returns). You should condition the actions and the give on the Take succeeding.