A graceful shutdown sequence helps your FreeRTOS system stop tasks and clean up resources safely before turning off or restarting.
Graceful shutdown sequence in FreeRTOS
void graceful_shutdown(void) {
// Notify tasks to stop
// Wait for tasks to finish
// Close peripherals
// Save data if needed
// Stop scheduler or enter low power mode
}This is a general structure; actual implementation depends on your tasks and hardware.
Use task notifications or flags to tell tasks to stop work.
void graceful_shutdown(void) {
// Signal tasks to stop
xTaskNotifyGive(taskHandle1);
xTaskNotifyGive(taskHandle2);
// Wait for tasks to confirm they stopped
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
// Close peripherals
close_uart();
close_spi();
// Save data
save_settings();
// Stop scheduler
vTaskEndScheduler();
}void graceful_shutdown(void) {
// Set a global flag
shutdown_requested = true;
// Tasks check this flag and stop themselves
// Wait some time for tasks to finish
vTaskDelay(pdMS_TO_TICKS(500));
// Power down hardware
power_down_peripherals();
// Enter low power mode
enter_sleep_mode();
}This program creates a worker task that runs and prints a message repeatedly. A shutdown task delays 500ms then calls graceful_shutdown(), which sets a flag to stop the worker task, waits for it to finish, then ends the scheduler.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> static TaskHandle_t taskHandle; static volatile int shutdown_requested = 0; void vTaskFunction(void *pvParameters) { while (!shutdown_requested) { // Do some work printf("Task running...\n"); vTaskDelay(pdMS_TO_TICKS(200)); } printf("Task stopping gracefully.\n"); vTaskDelete(NULL); } void vShutdownTask(void *pvParameters) { vTaskDelay(pdMS_TO_TICKS(500)); graceful_shutdown(); } void graceful_shutdown(void) { shutdown_requested = 1; // Wait for task to stop vTaskDelay(pdMS_TO_TICKS(500)); printf("Shutdown complete.\n"); vTaskEndScheduler(); } int main(void) { xTaskCreate(vTaskFunction, "Worker", 1000, NULL, 1, &taskHandle); xTaskCreate(vShutdownTask, "Shutdown", 1000, NULL, 1, NULL); vTaskStartScheduler(); return 0; }
Always ensure tasks check for shutdown signals regularly to stop quickly.
Use vTaskEndScheduler() only if your port supports it; some FreeRTOS ports do not.
FreeRTOS does not provide a built-in shutdown function; you must design your own sequence.
Graceful shutdown lets tasks stop safely and hardware close properly.
Use flags or notifications to tell tasks to stop work.
Wait for tasks to finish before powering down or stopping the scheduler.