Thinking in Interrupts: What It Really Takes to Write Reliable Firmware

Web developer habits meeting interrupts and bare-metal firmware

Your first interrupt-driven counter will probably work on the bench for an hour, then lose a count once every few million increments. The same logic in JavaScript would never drop a count, because only one callback runs at a time.

Plenty of web developers make this move and find it disorienting. The Ask HN thread “Tips for transitioning from web development to embedded/firmware?” is full of them. Most advice covers what to learn: pick up C, buy a dev board, read a book. You’ve probably already followed it.

This piece is for the next stage, when you’ve blinked the LED and your intuition keeps giving you wrong answers. My position: your discipline transfers, and your assumptions about execution, memory, and timing need replacing.

Interrupts, Memory, and Time

In JavaScript, a callback runs to completion. Once it starts, nothing else touches your state until it returns.

let count = 0;
setInterval(() => { count += 1; }, 10);
function handleClick() {
  count += 1; // no other callback can run between the read and the write
}

That’s why you never needed locks.

On a Cortex-M microcontroller, an interrupt can preempt your code between any two instructions. The NVIC (the interrupt controller built into every Cortex-M) saves a few registers, jumps to your interrupt service routine (ISR), then drops you back exactly where you were. Your function has no idea it was paused.

volatile uint32_t ticks = 0;
void SysTick_Handler(void) { ticks++; }   // ISR, fires every 1 ms

int main(void) {
  for (;;) {
    if (ticks >= 1000) {
      ticks -= 1000;   // load, subtract, store: the ISR can fire mid-way
      toggle_led();
    }
  }
}

ticks -= 1000 compiles to a load, a subtract, and a store. If the ISR fires after the load, its increment gets written over, and you’ve lost a tick.

JavaScript event loop (run-to-completion)
time ──────────────────────────────────────────────►
[ callback A ████████████ ][ callback B ██████ ][ timer cb ███ ]
  nothing interrupts A ─┘   timer waits its turn ─────┘

Bare-metal microcontroller (preemptive interrupts)
time ──────────────────────────────────────────────►
main loop:  ████████▌        ▐████████████▌    ▐█████
                    │  ISR   │            │ISR │
interrupt:          └▶█████──┘            └▶██─┘
            read x ──┘        └── write x   (x may have changed!)

volatile only stops the compiler from caching the variable in a register, and the race survives it. To make the update safe, wrap it in a critical section (__disable_irq() and __enable_irq() in CMSIS) or use an atomic operation.

Two more assumptions break when you leave the browser or Node.

Memory. You had a garbage collector and a heap that felt bottomless. An nRF52832 has up to 64 KB of RAM total, and your stack is a fixed slice of that, often 2 to 8 KB.

Time. Node’s timer docs say Node makes no guarantees about exactly when a timer callback fires. setTimeout(fn, 10) runs at some point after 10 ms, with no upper bound. A hardware timer is a contract: it fires on the configured tick, and if your code has a deadline, you have to prove you’ll meet it.

Async does exist in embedded. Rust’s Embassy gives you async/await on a microcontroller, and FreeRTOS and Zephyr give you tasks. The difference is who decides when you get interrupted: in Node it’s the runtime, at well-defined points; on a microcontroller it’s the hardware, whenever a signal arrives.

What Survives the Move to Embedded

Never block. “Don’t block the event loop” maps one-to-one onto “keep ISRs short.” An ISR should set a flag, push a byte into a ring buffer, or post to a queue, then return; the real work happens in the main loop or an RTOS task. If you already flinch at a synchronous file read in a request handler, you’ll flinch at a printf inside an ISR, and you should.

Event-driven design. Firmware runs on state machines: idle, advertising, connected, sleeping. If you’ve written a Redux reducer or modeled UI states, you already think this way, except the states control radios and power rails instead of spinners.

Debugging method. Reproduce, bisect, isolate. Only the tools change.

Put a thin hardware abstraction layer (HAL) between your logic and the registers, then run your logic tests on your laptop with a normal compiler. That’s the testing and abstraction habit, and web developers tend to do it better than plenty of career firmware engineers, whose codebases often mix register writes into business logic.

Version control, CI, and code review carry over fully, and a lot of embedded teams still practice them less rigorously than a typical web shop.

Reading docs. Datasheets and reference manuals are your API docs now. A reference manual can run past 1,000 pages and assumes you know what a pull-up resistor is, but you already know how to hunt for the one table that matters.

Instincts That Have to Die (or Get Retrained)

“Just allocate.” Many firmware projects ban malloc after init, and some ban it outright. You allocate buffers statically, size your stack up front, and live with fixed limits. A stack overflow on a microcontroller usually just overwrites whatever sits next to the stack, quietly, until something unrelated breaks.

“Just add a dependency.” Every library costs flash and RAM, and you can see the cost in your map file. Vendor HALs range from solid to buggy, and there’s no npm package for your chip’s errata. Check what a library adds to the binary before pulling it in.

A bad web deploy gets rolled back in minutes. A bad firmware update can brick a device sitting on a pole or in a shipping container. That’s why “ship it and patch later” needs retraining: bootloaders, A/B partitions, and rollback logic exist because a broken update means a truck roll, or a dead product.

“console.log it.” Printing over UART often takes milliseconds per line at 115200 baud, which changes your program’s timing and can make the race you’re chasing disappear while you watch. Learn a debug probe over SWD or JTAG (the debug interfaces built into the chip) so you can set breakpoints and inspect memory, and buy a cheap logic analyzer to see what the pins are actually doing.

“Exceptions will tell me.” C has undefined behavior, and by default a Cortex-M hard fault jumps to a handler that often loops forever, with no stack trace. Learn to read fault status registers early. Memfault’s Interrupt blog has the best practical write-ups on hard fault debugging I’ve found.

Web instinctVerdictFirmware form
Don’t block the event loop✅ KeepKeep ISRs short; defer work
Event-driven thinking✅ KeepState machines
Test with abstractions✅ KeepHAL + host-side unit tests
Run-to-completion safety❌ KillCritical sections, volatile, atomics
Allocate freely❌ KillStatic allocation, fixed stacks
npm install it🔁 RetrainWeigh every byte of flash/RAM
Ship and patch🔁 RetrainBootloaders, rollback, careful OTA
console.log debugging🔁 RetrainSWD/JTAG debugger, logic analyzer

The Embedded Linux Fork

Embedded work usually means one of two targets, and each punishes different instincts.

Embedded Linux keeps a lot of what you know: processes, a filesystem, sockets, a real allocator, and familiar languages. Python runs fine, and Node does too on a board with enough RAM. Userland async on Linux, with epoll under the hood, feels close to home.

It brings its own traps:

  • Cross-compiling. You build on x86 for an ARM target, and toolchain mismatches produce errors that read like nonsense the first time.
  • Yocto and Buildroot build an entire OS image from source. A first Yocto build can take hours and eat 50+ GB of disk.
  • Device trees and drivers. A device tree is a data file describing the hardware to the kernel. Once you write or patch a kernel driver, the interrupt rules from earlier come right back.
  • Boot time matters, root filesystems are often read-only, and verbose logging to flash can wear out an eMMC or SD card in the field.
   Bare-metal MCU                 Embedded Linux
 ┌──────────────────┐        ┌──────────────────────┐
 │  Your firmware   │        │ Your app (C/Py/Node) │ ← web instincts mostly OK
 ├──────────────────┤        ├──────────────────────┤
 │ HAL / RTOS (opt) │        │  Kernel + drivers    │ ← interrupt rules return
 ├──────────────────┤        ├──────────────────────┤
 │    Hardware      │        │ Bootloader / DTB     │
 └──────────────────┘        ├──────────────────────┤
  You own everything         │      Hardware        │
                             └──────────────────────┘

Bootlin’s free training slides are the reference for this path, covering everything from toolchains to kernel drivers.

My take: embedded Linux is the gentler on-ramp, and bare metal is where your mental model actually gets rebuilt. If you’re doing both, your instincts will be right more often on Linux. Just watch for the gaps that show up the moment you’re back on a microcontroller.

Four Exercises for Unlearning

Elecia White’s Making Embedded Systems covers what to learn; these exercises cover what to unlearn.

  1. Write a deliberately racy counter. Increment a variable in a timer ISR, decrement it in the main loop, and run it until the numbers drift. Then fix it with a critical section and watch the drift stop.
  2. Turn off the heap. Set the heap size to 0 or make malloc return NULL, then build a small project with static allocation only. For a sense of how a compact real-world firmware project is laid out, see this Zephyr RTOS reference application.
  3. Fix one bug without printf. Use a debug probe for breakpoints and a logic analyzer for pin timing. It’ll be slower the first time and faster every time after.
  4. On Linux, cross-compile one program and boot it in a Buildroot image before you touch Yocto. Buildroot is smaller, and you’ll understand what Yocto automates once you’ve done it by hand.

Keep the Discipline, Replace the Assumptions

Preemption, memory limits, and timer precision are all your problem in firmware, while your habits around testing, abstraction, and never blocking still apply. Start with the racy counter this week: watching a count drift on your own board will reset your instincts faster than any book.


Hubble Network lets your firmware connect devices over Bluetooth to a global satellite and terrestrial network without gateways, cellular modems, or new hardware. See how it works →