# Chapter 3: Implementing Context Switching ## Sample code - Directory: `docs/os-on-arduino/code/03_context_switch` ```bash uv run pio run -d 03_context_switch -t upload uv run pio device monitor -b 115200 ``` ## Source code The sketch for this chapter. Click a file name to expand. The code is mirrored automatically from the manuscript repository, so what you see here is always current. :::{dropdown} `src/main.cpp` — 176 lines :icon: code [Open on GitHub](https://github.com/iory/learning-os-from-arduino/blob/main/docs/os-on-arduino/code/03_context_switch/src/main.cpp) ```{literalinclude} ../../../../code/03_context_switch/src/main.cpp :language: cpp :linenos: ``` ::: :::{dropdown} `include/os_kernel.h` — 66 lines :icon: code [Open on GitHub](https://github.com/iory/learning-os-from-arduino/blob/main/docs/os-on-arduino/code/03_context_switch/include/os_kernel.h) ```{literalinclude} ../../../../code/03_context_switch/include/os_kernel.h :language: cpp :linenos: ``` ::: :::{dropdown} `src/os_kernel.cpp` — 200 lines :icon: code [Open on GitHub](https://github.com/iory/learning-os-from-arduino/blob/main/docs/os-on-arduino/code/03_context_switch/src/os_kernel.cpp) ```{literalinclude} ../../../../code/03_context_switch/src/os_kernel.cpp :language: cpp :linenos: ``` ::: ## On the board ```{figure} ../_static/ch03_yield.gif :name: fig-ch03-yield :width: 100% `Task1` (registered as LED1) → `Task2` (LED2) → `Task3` (Serial) keep handing over to each other. They go round about 8 times a second, so the output scrolls quickly. ``` ```{figure} ../_static/ch03_timing.svg :name: fig-ch03-timing :width: 100% When each of the three tasks has the CPU and when the LEDs are lit, over two rounds measured on the board. The tasks hand over with `os_yield()` and one round takes about 117 ms. The L LED is lit for only about 22 ms of that and the left half of the matrix for about 12 ms, which is why a video or a simulator GIF does not show them as blinking. (Measured by recording `micros()` timestamps inside each task; the extra measuring code is not part of the book's sample.) ``` ## Pitfalls (Collected from reader questions — ask via [GitHub Issues](https://github.com/iory/build-your-own-arduino-rtos/issues).)