In RTOS land, you split your app into tasks, tiny, schedulable functions that each do one job (e.g., read sensor, refresh display, handle keys). Here’s the clean, code-first way to write handlers, create tasks, pass data, and mind stacks/priorities.
✅ Task Handler (a schedulable function)
A task is just a C function that usually runs forever. If you ever leave the loop, delete yourself first.
๐️ Create a Task with xTaskCreate()
Pass handler, name, stack depth in words (not bytes), a parameter, priority, and an optional handle.
๐จ Passing Data to a Task
Give each task its own message via pvParameters. Cast back inside.
๐งต Local vs. static in Task Functions
-
Local (non-static) lives in the task’s private stack → each task instance gets its own copy.
-
staticlives in global data → shared across all instances.
๐ง Priorities (who runs first?)
-
Range:
0 .. (configMAX_PRIORITIES - 1)(set inFreeRTOSConfig.h). -
Higher number = higher urgency.
๐ Minimal Two-Task Demo
⚡ Pro Tips
-
Stack depth is in words, not bytes (
configSTACK_DEPTH_TYPE). 200 on Cortex-M ≈ 800 B. -
Check return:
configASSERT(xTaskCreate(...) == pdPASS); -
Keep handlers inside
for(;;); callvTaskDelete(NULL)if you must exit. -
Be stingy with large local arrays; they burn task stack.
-
Too many priority levels → more context switches → more RAM/time overhead.
-
In STM32Cube projects, put app code inside USER CODE BEGIN/END blocks.
๐ฏ Conclusion
Treat tasks as small, focused loops. Create them with clear priorities, right-sized stacks, and explicit parameters. Keep handlers lean, delete on exit, and your scheduler will stay happy.
Written By: Musaab Taha
This article was improved with the assistance of AI.
No comments:
Post a Comment