Skip to content

Commit f7d802d

Browse files
Continue adding more contents
1 parent c492a21 commit f7d802d

File tree

9 files changed

+2979
-2
lines changed

9 files changed

+2979
-2
lines changed

Communication_Protocols/High_Speed_Protocols.md

Lines changed: 714 additions & 0 deletions
Large diffs are not rendered by default.

Communication_Protocols/Protocol_Implementation.md

Lines changed: 804 additions & 0 deletions
Large diffs are not rendered by default.

Communication_Protocols/Wireless_Protocols.md

Lines changed: 781 additions & 0 deletions
Large diffs are not rendered by default.

README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,11 @@ Explore → [Advanced Hardware](#advanced-hardware) → [Embedded Security](#emb
9595

9696
#### **Phase 1: Real-Time Systems (6 weeks)**
9797
**RTOS Concepts**
98-
- **FreeRTOS Basics** - Task creation, scheduling, inter-task communication
99-
- **Task Creation and Management** - Task states, context switching, stack management
98+
- **[FreeRTOS Basics](./Real_Time_Systems/FreeRTOS_Basics.md)** - Determinism, tick, scheduler, kernel objects
99+
- **[Task Creation and Management](./Real_Time_Systems/Task_Creation_Management.md)** - Lifecycle, priorities, stack sizing, timing
100+
- **[Scheduling Algorithms](./Real_Time_Systems/Scheduling_Algorithms.md)** - RM, DM, EDF, schedulability, jitter
101+
- **[Interrupt Handling](./Real_Time_Systems/Interrupt_Handling.md)** - ISR design, priorities, FromISR APIs, latency
102+
- **[Kernel Services](./Real_Time_Systems/Kernel_Services.md)** - Queues, semaphores, mutexes, event groups, notifications
100103
- **Scheduling Algorithms** - Round-robin, priority-based, rate monotonic
101104
- **Interrupt Handling** - ISR design, interrupt latency, nested interrupts
102105
- **Kernel Services** - Semaphores, mutexes, message queues, event flags
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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+
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# 🧨 Interrupt Handling in RTOS-Based Systems
2+
3+
> Concepts for low-latency ISRs, nesting, priority mapping, and deferring work to tasks
4+
5+
## 📋 Table of Contents
6+
7+
- Overview
8+
- Interrupt Latency and Determinism
9+
- ISR Design Principles
10+
- Interrupt Priorities and Kernel Interaction
11+
- Deferring Work to Tasks
12+
- Synchronization From ISRs
13+
- Measuring and Tuning Latency
14+
- Best Practices and Pitfalls
15+
- Interview Questions
16+
17+
---
18+
19+
## 🎯 Overview
20+
21+
Interrupts handle urgent, asynchronous events with minimal latency. In RTOS systems, ISRs should be short and primarily signal tasks to perform the bulk of work. Proper priority configuration and correct use of FromISR APIs are essential for determinism.
22+
23+
---
24+
25+
## ⏱️ Interrupt Latency and Determinism
26+
27+
- **Sources of Latency**: Interrupt masking, critical sections, higher-priority ISRs, memory wait states.
28+
- **Determinism Goal**: Bound the worst-case latency; keep critical sections short and minimize nested work.
29+
- **Jitter**: Variability in latency; reduce by avoiding long non-preemptible sections and heavy ISRs.
30+
31+
---
32+
33+
## 🛠️ ISR Design Principles
34+
35+
- Do the minimum necessary in the ISR: capture timestamp/data, clear the source, and signal a task.
36+
- Avoid blocking, dynamic memory, or long loops in ISRs.
37+
- Ensure the ISR is reentrant or protect shared state.
38+
- Use volatile-qualified shared variables and atomics where required.
39+
40+
---
41+
42+
## 🎚️ Interrupt Priorities and Kernel Interaction
43+
44+
- On Cortex-M, lower numeric priority value = higher urgency; only priorities numerically larger (less urgent) than `configMAX_SYSCALL_INTERRUPT_PRIORITY` may call RTOS APIs.
45+
- The kernel may disable interrupts briefly for critical sections; keep those sections small in drivers.
46+
- Nesting: A higher-priority interrupt can preempt a lower one; keep nesting depth small to bound latency.
47+
48+
---
49+
50+
## 📬 Deferring Work to Tasks
51+
52+
Common patterns:
53+
- **Queue to Task**: Send a message from ISR to a worker task.
54+
- **Event Group**: Set bits to notify events.
55+
- **Stream/Message Buffer**: Transfer bytes/messages efficiently to a single receiver.
56+
- **Direct-to-Task Notifications**: Lightweight, fast signaling to a specific task.
57+
58+
Benefits: keeps ISRs short, leverages task priorities, and eases testing.
59+
60+
---
61+
62+
## 🔗 Synchronization From ISRs
63+
64+
- Use the `...FromISR` API variants (e.g., `xQueueSendFromISR`, `xTaskNotifyFromISR`).
65+
- Pass `pxHigherPriorityTaskWoken`/`xHigherPriorityTaskWoken` and request a context switch if needed.
66+
- Never use mutex APIs from ISRs; use semaphores or notifications. Mutexes implement priority inheritance and are task context only.
67+
68+
---
69+
70+
## 🔍 Measuring and Tuning Latency
71+
72+
- **Instrumentation**: Toggle a GPIO at ISR entry/exit and measure with a logic analyzer.
73+
- **Cycle Counters**: Use DWT cycle counter (Cortex-M) for fine-grained timing.
74+
- **Trace Tools**: Kernel trace to observe ISR-to-task wakeups and scheduling.
75+
- **Tuning**: Reduce critical sections, lower tick rate if it causes contention, optimize memory wait states.
76+
77+
---
78+
79+
## ✅ Best Practices and ⚠️ Pitfalls
80+
81+
Best Practices:
82+
- Keep ISRs short; defer to tasks.
83+
- Use the smallest interrupt priority capable of meeting latency needs.
84+
- Validate `configPRIO_BITS`, NVIC priorities, and `configMAX_SYSCALL_INTERRUPT_PRIORITY`.
85+
- Use direct-to-task notifications for fastest signaling.
86+
87+
Pitfalls:
88+
- Calling non-FromISR APIs in interrupt context.
89+
- Misconfigured NVIC priorities leading to hard faults or non-determinism.
90+
- Heavy computation in ISRs causing jitter and missed deadlines.
91+
92+
---
93+
94+
## 🎤 Interview Questions
95+
96+
1. What contributes to interrupt latency, and how do you bound it?
97+
2. Why should ISR work be minimized and deferred to tasks? How do you implement that?
98+
3. Which RTOS APIs are safe to call in an ISR and why?
99+
4. How do you configure NVIC priorities to work correctly with an RTOS?
100+
5. How would you measure ISR latency on a Cortex-M MCU?
101+
102+

0 commit comments

Comments
 (0)