Computers inside things
Count the computers in your home. The laptop and the phone are obvious; less so are the ones in the washing machine, the smoke alarm, the television remote, the electric toothbrush, the car key, and each of the dozens of control units in a modern car. Nearly all of these are microcontrollers: small, cheap computers built into a single chip together with the memory and the input–output hardware they need to sense and control the world. Industry surveys count tens of billions of them made every year, many times the number of laptop and phone processors.
In Designing a processor you built a CPU from registers, an ALU and a control unit. This lesson puts that CPU to work. We will see what else shares the chip with it, how a program written in C reaches out and changes the voltage on a physical pin, how the chip drops everything to respond to a button press within a fraction of a microsecond, and how the program gets from your laptop onto the chip in the first place. The language is C, the common tongue of embedded systems; Lumenary CS's C course teaches it, and its lessons on types and operators and pointers are the background you need.
Everything here is safe to try at your desk: a development board powered from a USB port runs at 3.3 or 5 V, and the usual worst case of a mistake is a dark LED.
What a microcontroller is
Definition— Microcontroller
A microcontroller (MCU) is a single integrated circuit containing a processor core, non-volatile program memory (usually flash), working memory (SRAM), a set of peripherals that connect the core to the outside world, and the clock, power and reset circuits that make the whole thing run, so that with a power supply and a few passive parts it is a complete, working computer.
The contrast is with the application processor in a phone or a Raspberry Pi computer: a much faster chip with a memory-management unit that needs external DRAM and runs an operating system such as Linux. A microcontroller trades speed for self-sufficiency, low power and predictability. Typical numbers in 2026: a core running at 16 to 500 MHz, 16 KB to a few megabytes of flash, 2 KB to about a megabyte of SRAM, and a power draw from a few milliwatts running down to a microwatt or less asleep.
The parts, in turn:
- The core. Most 32-bit microcontrollers in 2026 use an Arm Cortex-M core (M0+ for the smallest, M4 and M33 with a floating-point unit and DSP instructions in the middle, M7 and M85 at the top) or, increasingly, a RISC-V core; 8-bit families such as Microchip's AVR and PIC are still made in enormous numbers for simple jobs. Alongside the core sits an interrupt controller (the NVIC on Cortex-M; the CLIC or PLIC on RISC-V), which we meet below.
- Flash holds the program and constants with the power off. It is slow to write (erased in pages, and good for perhaps 10,000 to 100,000 erase cycles), so programs run from it but rarely change it; at high clock speeds reads need a cache or extra wait states.
- SRAM holds variables, the stack and buffers, and is lost at power-off. It is usually the scarcest resource.
- Peripherals are small, specialised hardware blocks that do jobs the core would otherwise have to do in software, in parallel with it: GPIO (general-purpose input and output pins), timers (counting, generating PWM, timestamping edges), serial interfaces (UART, SPI, I²C, CAN, USB: the subject of Buses and interfaces), analogue-to-digital converters (Sensors and data conversion), a DMA engine that copies data between peripherals and memory without the core, and often a radio.
- The clock tree generates and distributes clocks. A chip starts on an internal RC oscillator (cheap, accurate to about 1%), can switch to an external quartz crystal (accurate to tens of parts per million), and multiplies either with a phase-locked loop (PLL) up to the core frequency. Dividers then derive slower clocks for each bus and peripheral, and every peripheral's clock can be switched off — clock gating — to save power. That is why the first step in using any peripheral is to turn on its clock.
- Power, reset and debug: an internal voltage regulator, a brown-out detector that holds the chip in reset if the supply sags, the reset logic, and a debug port that lets a host computer halt the core, read memory and set breakpoints.
Example— Following a clock tree
A board has a 12 MHz crystal. The PLL multiplies it by 125 to get 1,500 MHz inside its oscillator, then divides by 6 and by 2 to give a 125 MHz system clock. (These are the default settings of the Raspberry Pi RP2040's system PLL.) A peripheral bus running at half that, 62.5 MHz, clocks a timer; with a prescaler of 625 the timer counts at 100 kHz, one tick every 10 µs. Every frequency in the chip comes from the crystal and shares its accuracy; change one divider and the baud rate, every PWM frequency and every delay change together.
Memory-mapped registers and bit manipulation
How does a program do anything to a pin? On almost every microcontroller the answer is the same: each peripheral's controls appear as registers at fixed addresses in the processor's address space, and the program reads and writes them with ordinary load and store instructions. This is memory-mapped I/O. A chip's reference manual is mostly a list of these registers, bit by bit.
Definition— Memory-mapped register
A memory-mapped register is a word of storage inside a peripheral that the processor accesses at a fixed address as though it were memory. Its bits, or groups of bits called fields, control the peripheral or report its state. Some registers are read–write; some are read-only (an input or a status flag); some are write-only (a command); and reading or writing some of them has side effects, such as clearing a flag or starting a conversion.
The basic skill of embedded programming is changing some bits of a register without disturbing the others. Four operations, each a Boolean identity from Logic gates and Boolean algebra applied to every bit at once, do almost everything. With mask = 1u << n selecting bit :
| Goal | C | Why it works |
|---|---|---|
| set bit | reg |= mask; | and |
| clear bit | reg &= ~mask; | and |
| toggle bit | reg ^= mask; | and |
| test bit | (reg >> n) & 1u or (reg & mask) != 0 | the AND keeps only bit |
| write field of width at | reg = (reg & ~(((1u << w) - 1) << s)) | (v << s); | clear the field, then OR in the new value |
The last line is the one people get wrong. Writing reg |= v << s alone cannot turn a 1 back into a 0, so a field that held 10 and is "set" to 01 ends up 11.
The Python model below is a GPIO port of an imaginary chip, with six registers that are typical of real ones: a MODE register with a 2-bit field per pin, an output latch OUT, an input register IN that reports the voltage actually on each pin, and three write-only registers SET, CLR and TGL that change only the bits you write as 1. Run it, then read the last part carefully.
class GPIOPort:
"""A model of one 16-pin GPIO port of an imaginary microcontroller.
Offset Name Access Meaning
0x00 MODE r/w 2 bits per pin: 00 input, 01 output, 10 alternate function, 11 analog
0x04 OUT r/w the output latch: what each output pin drives
0x08 IN read the voltage actually on each pin, as 0 or 1
0x0C SET write each 1 written sets that bit of OUT; 0s change nothing
0x10 CLR write each 1 written clears that bit of OUT
0x14 TGL write each 1 written flips that bit of OUT
"""
def __init__(self):
self.mode = 0
self.out = 0
self.external = 0b0000_0000_0000_0100 # a button with a pull-up holds pin 2 high
def read(self, offset):
if offset == 0x00: return self.mode
if offset == 0x04: return self.out
if offset == 0x08: # output pins read back their latch, inputs the world
outputs = sum(1 << p for p in range(16) if (self.mode >> 2 * p) & 3 == 1)
return (self.out & outputs) | (self.external & ~outputs & 0xFFFF)
return 0 # write-only registers read as zero
def write(self, offset, value):
value &= 0xFFFF_FFFF
if offset == 0x00: self.mode = value
elif offset == 0x04: self.out = value & 0xFFFF
elif offset == 0x0C: self.out |= value & 0xFFFF
elif offset == 0x10: self.out &= ~value & 0xFFFF
elif offset == 0x14: self.out ^= value & 0xFFFF
MODE, OUT, IN, SET, CLR, TGL = 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14
LED, BUTTON = 5, 2
gpio = GPIOPort()
# 1. Make pin 5 an output: clear its 2-bit field, then write 01 into it (read-modify-write).
m = gpio.read(MODE)
m = (m & ~(0b11 << 2 * LED)) | (0b01 << 2 * LED)
gpio.write(MODE, m)
print(f"MODE = {gpio.read(MODE):032b} (bits 11..10 = 01: pin 5 is an output)")
# 2. Set, clear and toggle with masks.
mask = 1 << LED
gpio.write(OUT, gpio.read(OUT) | mask); print(f"OUT |= mask -> {gpio.read(OUT):016b}")
gpio.write(OUT, gpio.read(OUT) & ~mask); print(f"OUT &= ~mask -> {gpio.read(OUT):016b}")
gpio.write(OUT, gpio.read(OUT) ^ mask); print(f"OUT ^= mask -> {gpio.read(OUT):016b}")
print("LED pin reads", (gpio.read(IN) >> LED) & 1, "| button pin reads", (gpio.read(IN) >> BUTTON) & 1)
gpio.external &= ~(1 << BUTTON) # someone presses the button: pin 2 pulled to 0
print("button pressed: pin 2 now reads", (gpio.read(IN) >> BUTTON) & 1)
# 3. The read-modify-write race. Main wants to turn on pin 7; an interrupt that
# turns on pin 3 happens to run between main's read and main's write.
gpio.write(OUT, 0)
for p in (3, 7):
gpio.write(MODE, gpio.read(MODE) | (1 << 2 * p))
value = gpio.read(OUT) # main: read ...
gpio.write(OUT, gpio.read(OUT) | (1 << 3)) # ... interrupt: OUT |= bit 3 ...
gpio.write(OUT, value | (1 << 7)) # ... main: modify and write back a stale copy
print(f"\nwith read-modify-write: OUT = {gpio.read(OUT):016b} pin 3 is {(gpio.read(OUT) >> 3) & 1}: the interrupt's update was lost")
gpio.write(OUT, 0)
gpio.write(SET, 1 << 7) # one write, nothing to interrupt
gpio.write(SET, 1 << 3)
print(f"with the SET register: OUT = {gpio.read(OUT):016b} pin 3 is {(gpio.read(OUT) >> 3) & 1}, pin 7 is {(gpio.read(OUT) >> 7) & 1}")The pressed button reads 0, not 1: the pin is pulled up to the supply through a resistor and the button connects it to ground, the usual arrangement because it needs no extra parts and is robust against noise. The last two lines show the classic embedded bug. In C, OUT |= mask compiles to three instructions — load, OR, store — and an interrupt can run between the load and the store. If the interrupt changes another bit of the same register, the main program then writes back its stale copy and silently undoes it. The bug is rare and vanishes under the debugger. Chip designers answer it in hardware with atomic set, clear and toggle registers: STMicroelectronics' STM32 parts have a bit set/reset register (BSRR), Nordic's nRF parts have OUTSET and OUTCLR, and the Raspberry Pi RP2040 and RP2350 have GPIO_OUT_SET, GPIO_OUT_CLR and GPIO_OUT_XOR. Some cores also offer bit-banding or atomic memory operations. Where none exists, the software must briefly disable interrupts around the read-modify-write.
A bare-metal blink, from reset to LED
"Bare metal" means no operating system and no vendor library: our code, the chip's registers and nothing in between. Everyone should do it once, because every library is built on exactly these steps. Our target is an imaginary Cortex-M chip, the L1, whose GPIO port A is the register block modelled above at address 0x4002_0000; real chips differ only in the addresses and names, which come from the reference manual. The code is not run here: it needs the board.
/* blink.c -- bare-metal LED blink for the imaginary L1 microcontroller.
Not run here: needs the board. Addresses are from the L1's (imaginary) reference manual. */
#include <stdint.h>
#define REG(addr) (*(volatile uint32_t *)(addr)) /* a register is a volatile word at a fixed address */
#define CLK_ENABLE REG(0x40010000u) /* clock gate: bit 0 feeds GPIO port A */
#define GPIOA_MODE REG(0x40020000u)
#define GPIOA_TGL REG(0x40020014u)
#define LED_PIN 5u
static void delay(uint32_t n)
{
while (n--) {
__asm volatile ("nop"); /* stops the compiler deleting the empty loop */
}
}
int main(void)
{
CLK_ENABLE |= 1u << 0; /* 1. switch on the port's clock */
GPIOA_MODE = (GPIOA_MODE & ~(3u << (2u * LED_PIN)))
| (1u << (2u * LED_PIN)); /* 2. pin 5 = output (field value 01) */
for (;;) { /* 3. forever: main never returns */
GPIOA_TGL = 1u << LED_PIN;
delay(1000000u);
}
}Three details carry the whole lesson. The REG macro turns an integer address into a pointer to a volatile 32-bit word: volatile tells the compiler that every read and every write in the source must really happen, in order, because the object can change, or act, outside the program's view. Without it an optimising compiler may keep the register in a CPU register, merge two writes into one, or delete a polling loop it thinks can never end. Second, the clock is enabled first; on most chips a peripheral with its clock gated off silently ignores writes. Third, main never returns, because there is nothing to return to.
But how does the chip get to main? On reset, a Cortex-M core reads two words from the start of its vector table: the initial stack pointer and the address of the reset handler. (A RISC-V core instead starts at a fixed reset address chosen by the chip designer.) The reset handler is ordinary C, usually supplied by the vendor as a "startup file":
/* startup.c -- what runs before main. Not run here: needs the board. */
#include <stdint.h>
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack; /* defined by the linker script */
int main(void);
void Reset_Handler(void)
{
uint32_t *src = &_sidata, *dst = &_sdata;
while (dst < &_edata) *dst++ = *src++; /* copy initial values of variables: flash -> RAM */
for (dst = &_sbss; dst < &_ebss; ) *dst++ = 0; /* C promises uninitialised statics start at 0 */
main();
for (;;) { }
}
void Default_Handler(void) { for (;;) { } } /* an unexpected interrupt: stop here for the debugger */
__attribute__((section(".isr_vector"), used))
void (* const vectors[16])(void) = {
(void (*)(void))&_estack, /* 0: initial stack pointer (top of RAM) */
Reset_Handler, /* 1: reset */
[2 ... 15] = Default_Handler, /* NMI, HardFault, ... SysTick (a GCC range extension) */
};A global such as int count = 7; must live in RAM, which is blank at power-on, so its initial value 7 is stored in flash and copied over before main runs; static int total; must start at 0, so its RAM is cleared. Those two loops are the C runtime's entire start-up on a microcontroller. A real vector table continues past entry 15 with one entry per peripheral interrupt, often a hundred or more.
On an Arduino the Arduino core library hides the registers behind pinMode, digitalWrite and delay, and supplies a main that calls your setup once and loop forever:
// Arduino sketch (C++). Not run here: needs the board.
const int LED_PIN = 13; // the on-board LED of an Arduino Uno
void setup() { pinMode(LED_PIN, OUTPUT); }
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(500); // milliseconds, timed by a hardware timer interrupt
digitalWrite(LED_PIN, LOW);
delay(500);
}Interrupts and interrupt service routines
A microcontroller spends its life waiting: for a byte, a button, a timer, an ADC conversion. It can poll, checking a status flag over and over, or ask the hardware to interrupt it when the event happens.
Definition— Interrupt, interrupt service routine
An interrupt is a hardware signal that makes the processor suspend the program it is running, save enough state to resume it, and jump to a function registered for that signal, the interrupt service routine (ISR, or handler). When the ISR returns, the processor restores the saved state and the interrupted program continues as if nothing had happened. Each source has an enable bit, a pending flag and usually a priority; a higher-priority interrupt may interrupt a lower-priority ISR (nesting).
On a Cortex-M the sequence is done entirely in hardware. A peripheral raises its interrupt line; the NVIC compares its priority with whatever is running; the core finishes (or abandons and later restarts) the current instruction, pushes eight registers onto the stack (r0–r3, r12, the link register, the program counter and the status register), fetches the handler's address from the vector table, and jumps. Arm documents this as 12 clock cycles on the Cortex-M3 and M4 when memory has no wait states, so an ISR can start 250 ns after the event at 48 MHz. Because the core saves exactly the registers a C function may clobber, an ISR is an ordinary C function. RISC-V microcontrollers do the same with a trap vector and, on many newer parts, the CLIC extension.
Here is the blink again, now timed by the SysTick timer, which almost every Cortex-M core has, always at the same architectural address:
/* Blink with a 1 ms timer interrupt. Not run here: needs the board. */
#define SYST_CSR REG(0xE000E010u) /* SysTick control and status */
#define SYST_RVR REG(0xE000E014u) /* reload value */
#define SYST_CVR REG(0xE000E018u) /* current value */
static volatile uint32_t ms_ticks; /* written by the ISR, read by main: must be volatile */
void SysTick_Handler(void) /* its address sits at entry 15 of the vector table */
{
ms_ticks++;
}
int main(void)
{
/* ... enable the port clock and make pin 5 an output, as before ... */
SYST_RVR = 16000u - 1u; /* 16 MHz / 16,000 = one interrupt per millisecond */
SYST_CVR = 0u;
SYST_CSR = 0x7u; /* bit 0 enable, bit 1 interrupt, bit 2 core clock */
uint32_t next = 500u;
for (;;) {
if ((int32_t)(ms_ticks - next) >= 0) { /* "has the deadline passed?", safe across wrap-around */
GPIOA_TGL = 1u << LED_PIN;
next += 500u;
}
__asm volatile ("wfi"); /* sleep until the next interrupt: saves power */
}
}The rules for writing ISRs follow from the fact that while one runs, everything of equal or lower priority waits:
- Keep it short. Read the data, clear the cause, set a flag or push into a buffer, return. Do the processing in the main loop or a task.
- Never block. No
delay, no waiting for another interrupt, noprintfto a slow serial port, and nomalloc, which is neither fast nor safe to re-enter. - Clear the interrupt flag. Many peripherals keep requesting until the ISR acknowledges them; forget, and the ISR runs again the instant it returns, forever.
- Share data carefully. A variable written in an ISR and read elsewhere must be
volatile, and if it is wider than the processor can read in one instruction, or is updated by a read-modify-write, the reader must disable interrupts briefly or use atomic operations. Lumenary CS's concurrency lesson calls this a data race; an ISR is a thread you did not start.
Polling or interrupts?
Neither approach always wins. Polling is simple, has no hidden concurrency and suits events that are frequent and regular; interrupts suit events that are rare, urgent or brief. The simulation compares them on 200 random "data ready" pulses, each 50 µs long, over 10 seconds, counting the latency from the event to the start of handling, the events missed entirely, and the fraction of the CPU's time spent.
import math
import random
rng = random.Random(7)
DURATION = 10.0 # seconds of simulated time
PULSE = 50e-6 # a sensor's "data ready" pulse lasts 50 microseconds
events = sorted(rng.uniform(0, DURATION) for _ in range(200))
CHECK = 2e-6 # CPU time to read a status register and test a bit
HANDLE = 5e-6 # CPU time to deal with one event (read the data, store it)
ENTRY_EXIT = 1e-6 # interrupt entry and return: about 48 cycles at 48 MHz
def polling(period, latched):
"""Check the pin (or a latched status flag) every `period` seconds."""
latencies, missed = [], 0
for t in events:
first_poll = math.ceil(t / period) * period # the next time the loop looks
if not latched and first_poll >= t + PULSE:
missed += 1 # the pulse came and went between looks
continue
latencies.append(first_poll - t)
busy = (DURATION / period) * CHECK + len(latencies) * HANDLE
return latencies, missed, busy
def interrupts():
latencies = [ENTRY_EXIT / 2] * len(events) # the core starts the handler within ~0.5 us
busy = len(events) * (ENTRY_EXIT + HANDLE)
return latencies, 0, busy
rows = [
("poll the pin every 10 ms", *polling(10e-3, latched=False)),
("poll the pin every 10 us", *polling(10e-6, latched=False)),
("poll a latched flag, 10 ms", *polling(10e-3, latched=True)),
("interrupt on the edge", *interrupts()),
]
print(f"{len(events)} events in {DURATION:.0f} s\n")
print(f"{'method':28} {'mean latency':>13} {'worst':>10} {'missed':>7} {'CPU busy':>9}")
for name, lat, missed, busy in rows:
mean = sum(lat) / len(lat) if lat else float("nan")
print(f"{name:28} {mean * 1e6:10.1f} us {max(lat) * 1e6:7.1f} us {missed:7d} {100 * busy / DURATION:8.3f}%")Polling the pin every 10 ms misses 199 of the 200 pulses: a 50 µs pulse is over long before the loop comes round. Polling every 10 µs catches them all, but spends 20% of the processor just looking. Polling a latched flag, which the hardware sets on the edge and keeps until software clears it, never misses an event but answers 5 ms late on average. The interrupt catches everything, starts in half a microsecond and costs the least CPU time of all. Polling still has its place: a control loop that runs every millisecond anyway can check its inputs for free, and polling cannot suffer an interrupt storm, in which a noisy input fires interrupts so fast that the main program never runs. There is also a third way, often the best for data: let DMA move every byte into a buffer and interrupt the core only when the buffer is full.
A related search every embedded programmer meets: choosing a timer's prescaler and period count to produce a frequency from the clock. The timer divides its input clock by the prescaler and then counts ticks, so , with and each limited to 16 bits on many parts.
from fractions import Fraction
def timer_settings(f_clk, f_target, max_count=65536):
"""Find a prescaler P and period count N (each 1..max_count) so f_clk / (P * N) is as close
as possible to f_target, preferring the smallest P (the finest timer resolution)."""
best = None
for p in range(1, max_count + 1):
n = round(Fraction(f_clk, p) / Fraction(f_target))
if not 1 <= n <= max_count:
continue
achieved = Fraction(f_clk, p * n)
error = abs(achieved - f_target) / Fraction(f_target)
if best is None or error < best[2]:
best = (p, n, error, achieved)
if error == 0:
break # exact, and no smaller prescaler did better
return best
f_clk = 48_000_000 # the timer's input clock, in hertz
print(f"timer clock {f_clk / 1e6:.0f} MHz\n")
print(f"{'wanted':>10} {'prescaler':>10} {'count':>7} {'achieved (Hz)':>16} {'error (ppm)':>12}")
for f in [1000, 50, 1, 44_100, 38_000, 7]:
p, n, err, achieved = timer_settings(f_clk, f)
print(f"{f:>10} {p:>10} {n:>7} {float(achieved):>16.4f} {float(err) * 1e6:>12.2f}")
print("\nregister values are usually one less: PSC = prescaler - 1, ARR = count - 1")A 1 kHz tick, a 50 Hz servo signal and a 1 Hz heartbeat come out exactly. The audio sample rate of 44.1 kHz cannot: is not an integer, so the best is 400 parts per million fast, which is why audio equipment uses crystals at multiples of 44.1 kHz, such as 11.2896 MHz. The 38 kHz carrier of an infrared remote control is 125 ppm off, far inside what its receiver tolerates.
The toolchain: from source to a running chip
Code for a microcontroller is compiled on a laptop for a different processor: it is cross-compiled. The pipeline:
- Cross-compiler. GCC or Clang/LLVM built for the target:
arm-none-eabi-gccfor Cortex-M ("none" meaning no operating system),riscv64-unknown-elf-gccor an LLVM toolchain for RISC-V. Flags select the exact core, for example-mcpu=cortex-m4 -mthumb -mfloat-abi=hard. - Linker and linker script. The linker joins the object files and places every section at an address. On a PC the operating system decides where a program lives; on a microcontroller the linker script must say where flash and RAM are, and which sections go where.
- Conversion and flashing.
objcopyturns the linked ELF file into a raw binary or Intel HEX image, and a programmer writes it into flash. Ways to flash differ by chip: a debug probe over SWD or JTAG (the universal method), a serial bootloader in ROM (Espressif's chips withesptool, Arduino's over USB serial), or a USB mass-storage bootloader: hold BOOTSEL on a Raspberry Pi Pico, plug it in, and copy a.uf2file onto the drive that appears. - Debugging. A debug probe (an open CMSIS-DAP design, SEGGER's J-Link, ST's ST-LINK, Espressif's built-in USB-JTAG on many recent chips) connects the host to the chip's debug port. OpenOCD or pyOCD translates between it and GDB, so you can halt the core, step through code, set breakpoints and watch variables and registers on the real hardware.
/* l1.ld -- a minimal linker script for the imaginary L1 (GNU ld syntax) */
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64K
}
SECTIONS
{
.isr_vector : { KEEP(*(.isr_vector)) } > FLASH /* the vector table must come first */
.text : { *(.text*) *(.rodata*) } > FLASH /* code and constants */
_sidata = LOADADDR(.data); /* where .data's initial values are stored */
.data : { _sdata = .; *(.data*) _edata = .; } > RAM AT > FLASH
.bss : { _sbss = .; *(.bss*) *(COMMON) _ebss = .; } > RAM
_estack = ORIGIN(RAM) + LENGTH(RAM); /* the stack grows down from the top of RAM */
}Building and flashing the blink then looks like this (OpenOCD needs a configuration file for your probe and one for your chip; it ships with files for hundreds of real ones):
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O2 -ffreestanding -nostdlib \
-T l1.ld startup.c blink.c -o blink.elf
arm-none-eabi-size blink.elf # text, data and bss: how much flash and RAM it uses
openocd -f interface/cmsis-dap.cfg -f target/your-chip.cfg \
-c "program blink.elf verify reset exit"SWD and JTAG. JTAG (IEEE 1149.1, from 1990) was designed to test the solder joints of boards by shifting bits through a chain of chips; it uses four signals, TCK, TMS, TDI and TDO, and was soon used for debugging too. Arm's Serial Wire Debug carries the same debug access over just two pins, SWCLK and SWDIO, which matters on a chip with 20 pins. Every board should bring these pins, with ground and the target voltage, to a small header: a board you cannot debug is a board you cannot finish. In production the same port flashes every unit, and the final firmware usually locks it.
Popular boards, and how to choose
A development board puts a microcontroller on a small PCB with a USB connector, a regulator, a crystal, a reset button, an LED or two and headers for every pin, often with a debug probe built in. Some widely used ones in 2026, from several makers and countries:
| Board | Maker | Microcontroller | Notes |
|---|---|---|---|
| Arduino Uno R3 / R4 | Arduino (Italy) | Microchip ATmega328P (8-bit AVR, 16 MHz, 2 KB RAM) / Renesas RA4M1 (Cortex-M4, 48 MHz, 32 KB RAM) | the beginner's standard, with a vast library and tutorial ecosystem; the R4 WiFi adds an Espressif radio module |
| Raspberry Pi Pico 2 | Raspberry Pi (UK) | RP2350: two Cortex-M33 or two Hazard3 RISC-V cores, 150 MHz, 520 KB RAM | programmable I/O state machines for custom interfaces; drag-and-drop flashing; inexpensive |
| ESP32-C3 / C6 boards | Espressif (China) | RISC-V core at 160 MHz with Wi-Fi and Bluetooth LE; the C6 adds 802.15.4 (Thread, Zigbee) | the usual choice for Wi-Fi gadgets; ESP-IDF framework built on FreeRTOS |
| STM32 Nucleo boards | STMicroelectronics (France and Italy) | dozens of STM32 parts, from Cortex-M0+ to M7 and M33 | built-in ST-LINK probe; widely used in industry and universities |
| nRF52840 DK / nRF54L15 DK | Nordic Semiconductor (Norway) | Cortex-M4F / Cortex-M33 with a RISC-V coprocessor, both with Bluetooth LE | low-power wireless; Nordic's SDK is built on Zephyr |
| Curiosity Nano boards | Microchip (USA) | 8-bit PIC and AVR, 32-bit SAM (Cortex-M) and PIC32 | small and cheap, with an on-board debugger |
| CH32V003 boards | WCH (China) | 48 MHz RISC-V, 16 KB flash, 2 KB RAM | among the cheapest 32-bit microcontrollers made; a good lesson in fitting code into very little memory |
Texas Instruments' LaunchPads (MSP430, MSPM0), NXP's FRDM boards, Infineon's PSoC kits and Silicon Labs' wireless kits are equally capable; the right one depends on the job.
Example— Choosing a chip for a greenhouse sensor
A school in Chile wants a sensor that measures temperature and humidity every minute, runs for two years on a coin cell and reports to a phone. Work through the requirements in order:
- Peripherals and pins: one I²C bus for a digital humidity sensor, one ADC input for soil moisture, an LED. Almost any MCU.
- Radio: Bluetooth LE to a phone, which narrows the field to wireless MCUs (Nordic nRF52 or nRF54, Silicon Labs EFR32BG, TI CC23xx, STM32WB, Espressif ESP32-C3 or C6).
- Power: a coin cell rules out Wi-Fi, whose current peaks are too high for it, and puts the sleep current with a running real-time clock at the top of the list: it should be a microamp or two (the arithmetic is in Real-time and low-power design).
- Memory and speed: the Bluetooth stack needs a few hundred kilobytes of flash; speed hardly matters.
- Software: Zephyr supports most of the candidates; pick the one whose examples and documentation the team finds clearest.
- Supply: choose a part its maker commits to producing for years, from more than one distributor; radio chips are simplest to use on a pre-certified module with its antenna.
Several chips meet every hard requirement, which is normal; the choice then falls to software, price and availability.
The professional view. Few products are written bare-metal throughout. Vendors supply hardware abstraction layers and SDKs (STM32Cube, the Pico SDK, ESP-IDF, nRF Connect SDK, MCUXpresso, Microchip's MPLAB Harmony), those for Cortex-M parts built on Arm's CMSIS headers. Real-time operating systems such as Zephyr and FreeRTOS add tasks, drivers and networking. Rust is now a serious option (The Embedded Rust Book, Embassy, RTIC), and MicroPython makes prototypes quick. Safety-critical teams follow coding standards such as MISRA C, test logic on the host first, and run hardware-in-the-loop tests in which a rig feeds real boards simulated inputs. Robots are a large consumer of all this: Lumenary Robotics' embedded control and safety lesson builds on it.
Common misconceptions
Misconception
"volatile makes a shared variable safe." It guarantees that every access in the source is performed, in order; it does not make a read-modify-write atomic, nor order accesses to other, non-volatile variables. Sharing data between an ISR and the main program also needs short critical sections or atomic operations.
Misconception
"Reading the output register tells me the pin's voltage." It tells you what the program asked for. The input register reports the pin itself, which can differ if the pin is configured as an input, is overloaded, or is shorted to something. Reading IN back is a simple self-test.
Misconception
"An ISR can do whatever main does." It runs with everything of lower priority frozen, can interrupt main between any two instructions, and must return quickly. Waiting, printing, allocating memory and calling non-re-entrant library functions from an ISR are classic sources of hangs and corruption.
A short history
Texas Instruments' TMS1000 of 1974 is usually counted as the first commercial microcontroller: a 4-bit processor with its ROM, RAM and I/O on one chip, built into calculators and toys. Intel's 8048 (1976) and 8051 (1980) made the idea universal, and 8051-compatible cores are still designed into chips today. Microchip's PIC and Atmel's AVR (1996), whose flash could be rewritten in the field, reached hobbyists, and in 2005 a group at the Interaction Design Institute Ivrea in Italy built the first Arduino on an AVR so that design students could program hardware. Arm's Cortex-M3 (2004) gave every vendor the same 32-bit core and toolchain; cheap Wi-Fi chips such as Espressif's ESP8266 (2014) followed; and in 2024 Raspberry Pi's RP2350 let the user choose at boot between Arm and RISC-V cores on the same chip.
Exercises
1. Microcontrollers
Warm-upHumanWhich C statement turns off bit 5 of the register CTRL and leaves every other bit unchanged?
2. Microcontrollers
Warm-upHumanAn 8-bit register starts at 0xA5. A program then runs
REG ^= 0x0F;
REG |= 0x40;
REG &= ~0x80;
What is REG afterwards, as a decimal number?
3. Microcontrollers
CoreComputationalWrite set_field(reg, shift, width, value), which returns the 32-bit register value reg with the width-bit field that starts at bit shift replaced by value, leaving every other bit unchanged. If value does not fit in width bits (or is negative), raise ValueError. The starter shows the common bug: it only ORs the value in.
4. Microcontrollers
CoreHumanThe SysTick timer counts down from its reload value to 0 and then interrupts, so it interrupts every (reload + 1) clock cycles. The core clock is 48 MHz. What reload value gives exactly one interrupt per millisecond?
5. Microcontrollers
CoreHumanA sensor signals 'data ready' with a 1 µs pulse on a pin, a few times a second at unpredictable moments. The main loop runs once every 10 ms. Which approach reliably catches every pulse without wasting the CPU?
6. Microcontrollers
CoreComputationalA program reads a 16-bit GPIO input register once per millisecond. Write edges(previous, current) that returns a pair (rising, falling) of 16-bit masks: rising has a 1 for every pin that was 0 in previous and is 1 in current; falling has a 1 for every pin that went from 1 to 0. Use bitwise operations, not a loop over pins.
7. Microcontrollers
CoreHumanarm-none-eabi-size firmware.elf prints
text data bss dec hex filename
12480 360 2104 14944 3a60 firmware.elf
How many bytes of RAM do the program's static variables occupy (not counting the stack and heap)?
8. Microcontrollers
Warm-upHumanOn a Cortex-M microcontroller with no operating system, what happens between reset and the first line of main?
Further reading and resources
- Arm Developer · ArmTechnical reference manuals for the Cortex-M cores, including the architecture reference manuals that define the exception model and SysTick.
- RISC-V ratified specifications · RISC-V InternationalThe open instruction set used by many newer microcontrollers, including its privileged architecture (traps and interrupts).
- Raspberry Pi microcontroller documentation · Raspberry Pi LtdDatasheets and SDK guides for the RP2040 and RP2350; unusually readable reference manuals.
- CMSIS 6 · ArmThe vendor-independent headers and interfaces every Cortex-M vendor builds on.
- The Embedded Rust BookBare-metal microcontroller programming in Rust, from registers to drivers.
- OpenOCDThe open-source on-chip debugger that talks to SWD and JTAG probes.
- Arduino documentation