Lessons and the learning game

Embedded C that survives

The C rules that keep a 2 KB chip alive, each broken on the Uno and then fixed: fixed-width types, volatile, flash, undefined behavior and MISRA style.

The bench

Every lesson opens one circuit: an Uno with a pushbutton on pin 2 (interrupt INT0, set not to bounce), a red lamp on pin 13 and a knob on A0.

Take the course at Embedded C that survives on /learn.

What each sketch does

  • ecdtypes prints the size of an int (2 bytes), overflows five minutes in milliseconds to -27680, wraps a uint8_t counter, and times an interval across the millis() wrap.
  • ecdvolatile sets a flag from the button's interrupt that loop() never sees until the flag is volatile, and reads a 4-byte counter with interrupts off.
  • ecdflash prints a help text and its free SRAM (1485 bytes), reads a sine table from PROGMEM, and gets 308 bytes back when the text is wrapped in F().
  • ecdub writes one element past an array into the alarm limit beside it, and shifts a 1 into the sign bit of a 16-bit int.
  • ecdheap builds a log with String until concat() fails at line 120, or in a fixed buffer that never touches the heap.
  • ecdrules is a heater's command parser written to MISRA-style rules, driven by typing SET and GET in the serial monitor.
  • ecdboss is a CubeSat telemetry sketch with three bugs to find and fix: an overflow, a missing volatile and a one-byte buffer overrun.

Why the bugs are real here

The Uno runs the same AVR instructions a real one does, built by clang at -Os with warnings treated as errors. So the int really is 16 bits, the missing volatile really leaves the flag in a register, literals really are copied to SRAM, and the heap really runs out. Where the compiler already catches a bug (an overflow of constants, a constant index past an array, an enum switch that misses a case) the sketches hide it behind a variable, as real bugs hide.

Honest limits

  • Undefined behavior depends on the compiler and its settings. The results here are what this compiler does; another compiler, or another optimization level, may do something else entirely, which is the point.
  • The MISRA rule numbers quoted are MISRA C:2012's. The standard itself is a paid document; the course states what each rule asks, not its exact text.
  • Mokxi's heap allocator merges free neighbors and picks the best fit, so fragmentation is milder than with some allocators; the String log still runs out of memory in about two seconds.

C from zero for the language itself, and Registers and assembly for what the compiler turns it into.