SemaphoreHandle_t mutex;
int globalCounter=0;
void setup() {
Serial.begin(115200);
mutex = xSemaphoreCreateMutex();
xTaskCreatePinnedToCore(Task1, "Task1", 1024,NULL, 2, NULL,1);
xTaskCreatePinnedToCore(Task2, "Task2", 1024, NULL, 1, NULL,1);
Serial.println("Task Created for Task1 and Task2.");
}
void loop() {}
void Task1(void *pvParameters)
{
while(1){
if (xSemaphoreTake(mutex, 10) == pdTRUE){
//timeout every 10 tick time
Serial.print(pcTaskGetName(NULL));
Serial.print(", Counter read value: ");
Serial.print(globalCounter);
globalCounter++;
Serial.print(", Updated value: ");
Serial.print(globalCounter);
Serial.println();
xSemaphoreGive(mutex);
}
//delay(1000);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void Task2(void *pvParameters){
while(1){
if (xSemaphoreTake(mutex, portMAX_DELAY) == pdTRUE){
//portMAX_DELAY -> without a timeout block.
//Actually take about 7 weeks
//if FreeRTOS is defined to tick every millisecond.
Serial.print(pcTaskGetName(NULL));
Serial.print(", Counter read value: ");
Serial.print(globalCounter);
globalCounter++;
Serial.print(", Updated value: ");
Serial.print(globalCounter);
Serial.println();
xSemaphoreGive(mutex);
}
//delay(250);
vTaskDelay(250 / portTICK_PERIOD_MS);
}
}