Bare metal: the super-loop and interrupts

The simplest firmware is a main loop and a few interrupt handlers, with no operating system. It handles more than you might expect.

Foundation

A super-loop, and interrupts pre-empting it Bare-metal firmware runs one main loop that polls inputs and does work in turn. A hardware event pre-empts the loop; its handler captures data and sets a flag, and a higher-priority interrupt can pre-empt that handler in turn. The main loop then sees the flag and processes the data. Super-loop, no operating system Poll inputs Do work repeat One main loop polls inputs and does work in turn. Interrupts let hardware events pre-empt the loop, as below. When interrupts arrive Main loop Low-priority interrupt handler High-priority interrupt handler polls, works sees the flag, processes the data captures data, sets a flag pre-empts the lower one (NVIC on Cortex-M) time Keep handlers short: a long one delays every other interrupt of equal or lower priority.
The main loop polls and works in turn; an interrupt handler pre-empts it just long enough to capture data and set a flag, and a higher-priority interrupt can pre-empt that handler.

Key points

  1. A bare-metal program runs one main loop that polls inputs and does work in turn, with no operating system; interrupts let hardware events pre-empt the loop.1
  2. Arm Cortex-M cores include a Nested Vectored Interrupt Controller (NVIC), which lets a higher-priority interrupt pre-empt a lower-priority one that is already running.2
  3. Interrupt handlers should do the minimum, such as capturing data and setting a flag, and leave processing to the main loop; long handlers delay every other interrupt of equal or lower priority.3421

Common mistakes

  • Sharing a variable between an interrupt and the main loop without protecting it, then chasing a bug that shows up once a day.