//Core
static const int app_cpu = 0;
//Global variable
static unsigned int count = UINT_MAX;
//Mutex
static SemaphoreHandle_t count_mutex;
//Task to decrease count
void vDec(void* param){
while(1){
//Lock count_mutex
xSemaphoreTake(count_mutex, portMAX_DELAY);
//Check if count cannot be decremented any more
if(count == 0){ break; }
//Decrement and print the result
--count;
Serial.print("Decremented. Current: ");
Serial.println(count);
//Unlock count_mutex, or tell if error occured
if(xSemaphoreGive(count_mutex) == pdFALSE){
Serial.println("ERROR OCCURED!");
}
//Delay 1sec
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void setup(){
//Init serial
Serial.begin(9600);
vTaskDelay(100 / portTICK_PERIOD_MS);
//Init mutex
count_mutex = xSemaphoreCreateMutex();
//Run first instance of vDec task
xTaskCreatePinnedToCore(
vDec,
"Decrease counter - 1",
1024,
NULL,
1,
NULL,
app_cpu
);
//Run second instance of vDec task
xTaskCreatePinnedToCore(
vDec,
"Decrease counter - 2",
1024,
NULL,
1,
NULL,
app_cpu
);
//Delete setup and loop task
vTaskDelete(NULL);
}
void loop(){
//Kosong
}