Design patterns help organize tasks so they work well together without problems. They make sure tasks share resources safely and run smoothly.
Why design patterns ensure reliable multi-tasking in FreeRTOS
/* Example: Using a mutex to protect shared resource */ SemaphoreHandle_t xMutex; void Task1(void *pvParameters) { for(;;) { if(xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE) { // Access shared resource safely xSemaphoreGive(xMutex); } vTaskDelay(100 / portTICK_PERIOD_MS); } }
Design patterns often use FreeRTOS features like mutexes, queues, and semaphores.
They help tasks avoid stepping on each other's toes when sharing resources.
/* Using a queue to send data between tasks */ QueueHandle_t xQueue; void SenderTask(void *pvParameters) { int data = 100; xQueueSend(xQueue, &data, portMAX_DELAY); }
/* Using a mutex to protect shared variable */ SemaphoreHandle_t xMutex; int sharedVar = 0; void Task(void *pvParameters) { if(xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE) { sharedVar++; xSemaphoreGive(xMutex); } }
This program creates a mutex to protect a shared counter. One task increments the counter safely every 500 milliseconds and prints its value. The mutex ensures no other task can change the counter at the same time, preventing errors.
#include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include <stdio.h> SemaphoreHandle_t xMutex; int sharedCounter = 0; void vTaskIncrement(void *pvParameters) { for(;;) { if(xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE) { sharedCounter++; printf("Counter: %d\n", sharedCounter); xSemaphoreGive(xMutex); } vTaskDelay(500 / portTICK_PERIOD_MS); } } int main(void) { xMutex = xSemaphoreCreateMutex(); if(xMutex == NULL) { printf("Mutex creation failed\n"); return 1; } xTaskCreate(vTaskIncrement, "IncrementTask", 1000, NULL, 1, NULL); vTaskStartScheduler(); for(;;); return 0; }
Always use synchronization tools like mutexes or queues to avoid data corruption.
Design patterns make your multi-tasking code easier to read and less error-prone.
Testing your tasks together helps catch timing or resource conflicts early.
Design patterns organize tasks to work together safely and reliably.
They use FreeRTOS tools like mutexes and queues to manage shared resources.
Following these patterns helps prevent crashes and makes code easier to maintain.