How it works
Modern C++ for microcontrollers is an advanced course for people who can already write a sketch with classes. Every lesson runs on an ESP32-C3, a 160 MHz 32-bit RISC-V chip with 400 KB of RAM, with an LED on GPIO 8 and a button on GPIO 9.
Each lesson opens a working sketch that prints what it is doing: sizes, call counts, timings, the order destructors run in. You run it, read the serial monitor, then change it and run again. The checks read the serial output and the LED. Where a lesson talks about code size, it quotes the build panel's "Sketch uses" line, and you watch the number move yourself.
The lessons
- constexpr: a Fibonacci number the compiler works out against the 21891
calls it takes on the chip, a lookup table built at build time, and
static_assertrefusing a blink rate that is too fast. - enum class: an airlock state machine in a one-byte scoped enum, what a plain enum gets wrong, and the compiler finding every switch a new state touches.
- std::array: zero overhead against a C array, the decay bug it stops,
range-for,
std::sort, and whatat()does with exceptions turned off. - RAII: a lamp guard that survives an early return, a scoped timer that reports itself, destruction order, and fixing a hand-written version that leaves the lamp on.
- Lambdas: a sort by distance from the Sun, a task table of captureless lambdas, captures by value and by reference, and the size of each one in bytes.
- Templates without bloat: an array template of your own, ring buffers of four sizes, and the shared-base trick, measured: less code, a little more RAM.
The project: a zero-cost pin driver
OutputPin<8> puts the pin number in the type, so every call compiles to one
write to the chip's set or clear register. It races digitalWrite and wins
by more than ten times, it has no data at all, and a Blinker<Led, 500>
builds on it with the rate as a template parameter. You write the input half,
InputPin<9>, then make the driver yours: a toggle, active-low pins, or a
build-time check for pin conflicts.
What the ESP32-C3 engine does differently
- The runtime is Mokxi's own: no libc and no full C++ library. It ships a
small standard library of its own (
<array>,<algorithm>,<utility>,<functional>and more), sized for a microcontroller. - Every build uses
-fno-exceptionsand-fno-rtti, as most embedded C++ does.std::array::at()past the end gives the last element instead of throwing; check indexes yourself. - Timings from
micros()come from the simulated clock. They are steady from run to run, and can differ by a few percent between the editor's compiler and the prebuilt examples, so the lessons say "about". - Code and variables share the C3's RAM, and the build log says so under its numbers.
After this course
Multi-file C covers the headers, macros and linker underneath all of this, and the firmware capstone puts it to work on a full device.