'Im trying to Implement a Mutex in FreeRTOS using arduino but my output isnt coming out right

Here i defined the handles and task prototypes

void Task1(void *p);
void Task2(void *p);

TaskHandle_t Task1_handle;
TaskHandle_t Task2_handle;
SemaphoreHandle_t myMutex;

Here is the setup function with the task and mutex creation functions

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  myMutex = xSemaphoreCreateMutex();
  if(myMutex == NULL)
  {
    Serial.println("Mutex cannot be created");
  }
  xTaskCreate(Task1, "Task 1", 100, NULL, 1, &Task1_handle);
  xTaskCreate(Task2, "Task 2", 100, NULL, 1, &Task2_handle);
  vTaskStartScheduler();
}

void loop() {
  // put your main code here, to run repeatedly:

}

Here are the tasks i created

void Task1(void *p)
{
  (void) p;
  while(1)
  {
    xSemaphoreTake(myMutex, portMAX_DELAY);
    Serial.println("task 1");
    for(int i = 0; i < 5; i++)
    {
      Serial.println(i);
      vTaskDelay(500 / portTICK_PERIOD_MS);
    }
    xSemaphoreGive(myMutex);
  }
}

void Task2(void *p)
{
  (void) p;
  while(1)
  {
    xSemaphoreTake(myMutex, portMAX_DELAY);
    Serial.println("task 2");
    for(int i = 0; i < 5; i++)
    {
      Serial.println(i);
      vTaskDelay(500 / portTICK_PERIOD_MS);
    }
    xSemaphoreGive(myMutex);
  }
}

This is my code so far, but i dont seem to be getting my second task on the serial monitor: Serial Monitor Output

Am i using the semaphore function wrong?



Solution 1:[1]

The mutex is locked while the Task 1 is sleeping, so Task 2 can never get the mutex. The section that is guarded by the mutex should be as short as possible, for example:

void Task1(void *p)
{
    (void)p;
    while (1) {
        xSemaphoreTake(myMutex, portMAX_DELAY);
        Serial.println("task 1");
        xSemaphoreGive(myMutex);
        for (int i = 0; i < 5; i++) {
            xSemaphoreTake(myMutex, portMAX_DELAY);
            Serial.println(i);
            xSemaphoreGive(myMutex);
            vTaskDelay(500 / portTICK_PERIOD_MS);
        }
    }
}

Modify the Task 2 in the same way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Armandas