I understood if we want to protect resource we can use mutex or Semaphore I have gone through documents avillable for freertos but I don’t understand what ( mutex or Semaphore ) to use in which situation ?
I have written and tested code for mutex or Semaphore I think both looks same the only difference is in coding style.
ESP32, arduino IDE
Mutex
/* Include FreeRTOS APIs and defines */
#include <mutex>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
SemaphoreHandle_t mutex = xSemaphoreCreateMutex();
const int RED = 4;
void setup()
{
assert(mutex);
Serial.begin(115200);
pinMode(RED, OUTPUT);
xTaskCreatePinnedToCore(Task1, "Task1", 1000, NULL, 1, NULL, 0);
xTaskCreatePinnedToCore(Task2, "Task2", 1000, NULL, 1, NULL, 0);
}
void Task1( void * parameter )
{
for(;;)
{
xSemaphoreTake(mutex, portMAX_DELAY);
digitalWrite( RED, HIGH);
vTaskDelay( 400 );
digitalWrite( RED, LOW);
vTaskDelay( 400 );
xSemaphoreGive(mutex);
}
}
void Task2( void * parameter )
{
for(;;)
{
xSemaphoreTake(mutex, portMAX_DELAY);
digitalWrite(RED, HIGH);
vTaskDelay( 500 );
digitalWrite(RED, LOW);
vTaskDelay( 500 );
xSemaphoreGive(mutex);
}
}
void loop() {}
Semaphore
/* Include FreeRTOS APIs and defines */
#include <mutex>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
SemaphoreHandle_t mutex = xSemaphoreCreateMutex();
const int RED = 4;
void setup()
{
assert(mutex);
Serial.begin(115200);
pinMode(RED, OUTPUT);
xTaskCreatePinnedToCore(Task1, "Task1", 1000, NULL, 1, NULL, 0);
xTaskCreatePinnedToCore(Task2, "Task2", 1000, NULL, 1, NULL, 0);
}
void Task1( void * parameter )
{
for(;;)
{
xSemaphoreTake(mutex, portMAX_DELAY);
digitalWrite( RED, HIGH);
vTaskDelay( 400 );
digitalWrite( RED, LOW);
vTaskDelay( 400 );
xSemaphoreGive(mutex);
}
}
void Task2( void * parameter )
{
for(;;)
{
xSemaphoreTake(mutex, portMAX_DELAY);
digitalWrite(RED, HIGH);
vTaskDelay( 500 );
digitalWrite(RED, LOW);
vTaskDelay( 500 );
xSemaphoreGive(mutex);
}
}
void loop() {}
Can anyone give me situation where it can be figured out weather to use mutex or Semaphore