Manage FreeRTOS tasks - Suspend, Delay, Resume, Delete

Once you have FreeRTOS tasks running, you might want to manage them. The scheduler can stop, suspend, and resume individual tasks. You can control tasks from within or you can use task handles to control them from anywhere in your code.

Task handles

Using task handles:

// Define a task handle and initialize it to NULL
TaskHandle_t task_handle = NULL;

// Create the task, and pass the task handle as last parameter
// to xTaskCreate (pointer):
xTaskCreate(
task1, // Function that should be called
"Task 1", // Name of the task (for debugging)
1000, // Stack size (bytes)
NULL, // Parameter to pass
1, // Task priority
&task1_handle // Task handle
);

Stopping a task

// From within the task itself:
vTaskDelete(NULL);

// From the outside (with a task handle)
vTaskDelete(task_handle);

Suspending & resuming a single task

// Suspend a task within the task itself:
vTaskSuspend(NULL);

// Suspend a task from the outside
vTaskSuspend(task_handle);

// Resume a task (only possible from the outside)
vTaskResume(task_handle);

Suspend all tasks & resume all tasks

If you have time-sensitive code, you might want to temperorily pause all other tasks while executing it.

void superImportantTask(){
vTaskSuspendAll();

// Do something really important here
// (Code that's timing sensitive and should
// not be interrupted by FreeRTOS)

// Resume all tasks again
xTaskResumeAll();
}

Useful resources