|
| 1 | +# 🧠 FreeRTOS Basics |
| 2 | + |
| 3 | +> Understanding the core ideas of an RTOS and how FreeRTOS applies them in embedded systems |
| 4 | +
|
| 5 | +## 📋 Table of Contents |
| 6 | + |
| 7 | +- **Overview** |
| 8 | +- **What is an RTOS?** |
| 9 | +- **Why FreeRTOS?** |
| 10 | +- **Core Concepts** |
| 11 | +- **FreeRTOS Architecture at a Glance** |
| 12 | +- **Timing and the Kernel Tick** |
| 13 | +- **Task Model and States** |
| 14 | +- **Memory and Footprint** |
| 15 | +- **ISRs vs Tasks** |
| 16 | +- **Best Practices and Pitfalls** |
| 17 | +- **Quick Example** |
| 18 | +- **Interview Questions** |
| 19 | + |
| 20 | +--- |
| 21 | + |
| 22 | +## 🎯 Overview |
| 23 | + |
| 24 | +Real-Time Operating Systems (RTOS) enable deterministic, predictable execution under constraints like deadlines and bounded latency. FreeRTOS is a lightweight, portable RTOS widely used on MCUs for task scheduling, synchronization, and timing services. |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +## 🤔 What is an RTOS? |
| 29 | + |
| 30 | +- **Determinism**: Bounded response time to events. |
| 31 | +- **Preemption**: Higher-priority tasks can preempt lower-priority tasks. |
| 32 | +- **Scheduling**: Selects the next task to run based on priority and state. |
| 33 | +- **Time Services**: Delays, timeouts, periodic work. |
| 34 | +- **Synchronization**: Safe coordination between concurrent tasks and ISRs. |
| 35 | + |
| 36 | +RTOS ≠ “fast”; it is “predictable.” Deterministic latency is the goal. |
| 37 | + |
| 38 | +--- |
| 39 | + |
| 40 | +## 💡 Why FreeRTOS? |
| 41 | + |
| 42 | +- **Portable**: Supports many MCU families and toolchains. |
| 43 | +- **Small Footprint**: Fits into tens of KB of Flash/RAM. |
| 44 | +- **Familiar APIs**: Simple C interface for tasks, queues, semaphores, timers. |
| 45 | +- **Configurable**: Tune features via `FreeRTOSConfig.h`. |
| 46 | +- **Ecosystem**: Rich examples, community, and commercial support (FreeRTOS+). |
| 47 | + |
| 48 | +--- |
| 49 | + |
| 50 | +## 🧠 Core Concepts |
| 51 | + |
| 52 | +- **Task**: Independent execution context with its own stack and priority. |
| 53 | +- **Scheduler**: Preemptive priority-based (optional time-slicing among equal priorities). |
| 54 | +- **Tick**: Periodic interrupt that advances time and drives delays/timeouts. |
| 55 | +- **Ready List**: Per-priority queues of tasks ready to run. |
| 56 | +- **Blocked State**: Task waits on time, queue, semaphore, event group, etc. |
| 57 | +- **Critical Sections**: Temporarily suspend preemption for short, atomic work. |
| 58 | +- **Synchronization Primitives**: Queues, semaphores (binary/counting), mutexes (with priority inheritance), event groups, stream/message buffers. |
| 59 | +- **Software Timers**: Deferred work executed in a timer service task. |
| 60 | + |
| 61 | +--- |
| 62 | + |
| 63 | +## 🏗️ FreeRTOS Architecture at a Glance |
| 64 | + |
| 65 | +``` |
| 66 | +Application Tasks ─┐ ┌─> Queues/Semaphores/Mutexes/EventGroups |
| 67 | + │ │ |
| 68 | +Software Timers ───┼──┤ (Kernel objects in RAM) |
| 69 | + │ │ |
| 70 | +Idle Task ───┘ └─> Scheduler (priority-based, preemptive) |
| 71 | + ↑ |
| 72 | + │ |
| 73 | + SysTick/Timer ISR (kernel tick) |
| 74 | +``` |
| 75 | + |
| 76 | +- Each task has a TCB (Task Control Block) + stack. |
| 77 | +- The scheduler selects the highest-priority READY task. |
| 78 | +- The tick interrupt updates delays, unblocks expired tasks, and may trigger a context switch. |
| 79 | + |
| 80 | +--- |
| 81 | + |
| 82 | +## ⏱️ Timing and the Kernel Tick |
| 83 | + |
| 84 | +- **Tick Rate (`configTICK_RATE_HZ`)**: Commonly 100–1000 Hz. |
| 85 | +- **Delays**: `vTaskDelay`, `vTaskDelayUntil` use ticks; accuracy is ±1 tick. |
| 86 | +- **Tickless Idle**: Suppress periodic ticks while idle to save power; requires a wake-up source. |
| 87 | +- **Timeouts**: All blocking APIs accept timeouts (in ticks) for deterministic waits. |
| 88 | + |
| 89 | +Design tip: Choose a tick rate that balances timing resolution vs. CPU overhead and power. |
| 90 | + |
| 91 | +--- |
| 92 | + |
| 93 | +## 🔁 Task Model and States |
| 94 | + |
| 95 | +States: READY ↔ RUNNING ↔ BLOCKED ↔ SUSPENDED |
| 96 | + |
| 97 | +- **READY**: Eligible to run; waiting for CPU based on priority. |
| 98 | +- **RUNNING**: Currently executing on the CPU. |
| 99 | +- **BLOCKED**: Waiting on time or a kernel object (queue/semaphore/event group). |
| 100 | +- **SUSPENDED**: Not scheduled until explicitly resumed. |
| 101 | + |
| 102 | +Priorities are integer levels; higher value = higher priority (port-dependent). Starvation is possible if a very high-priority task never blocks. |
| 103 | + |
| 104 | +--- |
| 105 | + |
| 106 | +## 🧮 Memory and Footprint |
| 107 | + |
| 108 | +- **Per-task Stack**: Size depends on worst-case call depth and ISR usage via `portSAVE_CONTEXT`/`portRESTORE_CONTEXT`. |
| 109 | +- **Kernel Heap**: Selected by `heap_1`..`heap_5`: |
| 110 | + - `heap_1`: Static bump allocator (no free). Smallest, fastest. |
| 111 | + - `heap_2`: Free with coalescing. Simple fragmentation handling. |
| 112 | + - `heap_3`: Wraps `malloc/free`. Depends on C library. |
| 113 | + - `heap_4`: Best-fit with coalescing. Good fragmentation characteristics. |
| 114 | + - `heap_5`: Multiple non-contiguous regions. Flexible for constrained MCUs. |
| 115 | +- **Idle Hook / Malloc Failed Hook / Stack Overflow Hook**: Enable for diagnostics. |
| 116 | + |
| 117 | +Choose stack sizes by measurement (watermarking) and enable stack overflow checking. |
| 118 | + |
| 119 | +--- |
| 120 | + |
| 121 | +## ⚡ ISRs vs Tasks |
| 122 | + |
| 123 | +- ISRs should be minimal: capture data/state and defer processing to tasks (via queues/stream buffers/event groups). |
| 124 | +- Use the “FromISR” API variants inside interrupts. |
| 125 | +- Ensure correct interrupt priority configuration (only permissive priorities may call FreeRTOS APIs; depends on port and `configMAX_SYSCALL_INTERRUPT_PRIORITY`). |
| 126 | + |
| 127 | +--- |
| 128 | + |
| 129 | +## ✅ Best Practices and ⚠️ Pitfalls |
| 130 | + |
| 131 | +Best Practices: |
| 132 | +- Keep high-priority tasks short and frequently blocking. |
| 133 | +- Assign priorities by criticality and latency, not by feature importance. |
| 134 | +- Use bounded queues and timeouts; avoid infinite blocking. |
| 135 | +- Instrument: enable run-time stats and stack high-water marks. |
| 136 | +- Prefer event-driven designs over tight polling. |
| 137 | + |
| 138 | +Pitfalls: |
| 139 | +- Priority inversion without mutexes that implement priority inheritance. |
| 140 | +- Oversized tick rate increasing power and CPU overhead. |
| 141 | +- Excessive heap fragmentation (use `heap_4`/`heap_5` or static allocations). |
| 142 | +- Doing heavy work in ISRs or high-priority tasks leading to starvation. |
| 143 | + |
| 144 | +--- |
| 145 | + |
| 146 | +## 🧪 Quick Example (conceptual) |
| 147 | + |
| 148 | +```c |
| 149 | +// Two cooperative tasks using delays; conceptual snippet only |
| 150 | +void vBlinkTask(void* arg) { |
| 151 | + for (;;) { |
| 152 | + led_toggle(); |
| 153 | + vTaskDelay(pdMS_TO_TICKS(500)); // periodic blink |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +void vButtonTask(void* arg) { |
| 158 | + for (;;) { |
| 159 | + if (button_pressed()) { |
| 160 | + xQueueSend(xEvents, &(int){1}, 0); |
| 161 | + } |
| 162 | + vTaskDelay(pdMS_TO_TICKS(10)); // debounce period |
| 163 | + } |
| 164 | +} |
| 165 | +``` |
| 166 | +
|
| 167 | +Focus: periodic work with `vTaskDelay`, event passing via a queue, and short duty cycles so higher-priority tasks can preempt. |
| 168 | +
|
| 169 | +--- |
| 170 | +
|
| 171 | +## 🎤 Interview Questions |
| 172 | +
|
| 173 | +1. What makes an RTOS “real-time” and how is that different from “fast”? |
| 174 | +2. Explain the role of the kernel tick and how tickless idle works. |
| 175 | +3. Describe task states and how tasks transition between them. |
| 176 | +4. How would you size task stacks and select a heap scheme on a constrained MCU? |
| 177 | +5. Why should ISR work be minimized and deferred? How is that implemented in FreeRTOS? |
| 178 | +
|
| 179 | +--- |
| 180 | +
|
| 181 | +Next: See `Task_Creation_Management.md` for deeper task lifecycle, priorities, and stack management. |
| 182 | +
|
| 183 | +
|
0 commit comments