Embedded Systems

A stop button must cut a motor within 10 ms. A superloop with 20 ms of work per pass checks the button once per pass, so half the presses are late. An interrupt answers in under a microsecond, and the chip sleeps the rest of the time.

Pick a firmware design, then drag the work per pass. Watch where each press lands against the 10 ms line, and how long the battery lasts. Then we build, piece by piece, the chip, its registers, pins, timers, interrupts, the ADC, the buses and the structure that holds them together.

You need a little C or Python and binary numbers. We build the rest from zero.

Lesson 1 of the Embedded Systems series. Next: Lesson 2, Embedded C. The hands-on track is Firmware from Zero.

Answer the stop button in time

20.1 ms

Illustrative toy. The 10 ms deadline, a 10 mA run current, a 0.05 mA sleep current and a 2,000 mAh battery are made-up round numbers. The interrupt design wakes on a 100 ms timer tick to do its work. Interrupt entry is 12 cycles on a Cortex-M3 with zero-wait-state memory (Arm), 0.17 µs at 72 MHz.

Chapter 0

One Job, One Deadline, a Small Budget

Count the clock cycles that fit before the deadline, and see why the count decides the design

A conveyor has a stop button. The spec says the motor must stop within 10 ms of a press. The first firmware blinks a status LED with delay(500) and checks the button between blinks. Nothing crashes. The code is correct line by line. A press can still wait half a second.

That is the whole subject in one bug. An embedded system is a computer built into a product to do one job. It usually has no operating system between your code and the hardware, so your code is the system. It has little memory, a power budget, and deadlines: times by which an answer must exist, or the answer is wrong.

Fit the job inside its deadline

Pick a job. The yellow bar is the cycles the clock gives you before the deadline; the warm bar is the cycles the job needs. Turn the clock up until the work fits.

16 MHz

Illustrative jobs. The work counts (50,000, 2,000, 40,000 and 30,000 cycles) are made up; real counts come from measuring your own code.

How much computing fits before a deadline? Call the CPU's clock frequency, the number of cycles it runs each second, f. Call the time until the deadline T. The number of cycles you get is N:

Say it aloud

N equals f times T.

N
N the cycle budget: how many clock cycles run before the deadline. A simple instruction takes one or a few cycles.
f
f the CPU clock frequency, in cycles per second (hertz). 72 MHz is 72 million.
T
T the time until the deadline, in seconds.
In plain words

Multiply the clock rate f by the time T you have. The product N is every cycle you can spend. If the job needs more than N cycles, it misses the deadline every time.

With numbers

A 1 kHz drone loop gives T = 1 ms. At f = 72 MHz, N = 72,000 cycles. At 16 MHz, N = 16,000. A filter that needs 40,000 cycles fits the first chip and never fits the second.

ConstraintA laptopA small embedded system (illustrative)
Memorygigabyteskilobytes to a few hundred kilobytes
Clocka few GHztens to hundreds of MHz
Powertens of wattsmilliwatts, microwatts when asleep
Timing"fast on average"a deadline, every time
Softwarean operating systembare metal, or a small real-time OS

Symptom: the board meets its deadlines on the bench, then misses them after one more feature.

Measure: set a spare pin high at the start of the job and low at the end. A logic analyser shows the pulse width: the job's real time, worst case included.

Fix: keep a budget per deadline, N = f T, and keep the measured worst case well under it.

The road

  1. MCU vs MPU: the whole computer on one chip.
  2. Registers: every peripheral is an address.
  3. GPIO: a pin you configure, an LED, a button.
  4. Timers: count hardware ticks, make PWM.
  5. Interrupts: let the hardware call your code.
  6. ADC: turn a voltage into a number.
  7. Buses: UART, SPI and I²C.
  8. Structure: superloop, flags, state machine, sleep. The hero's numbers come from here.
  9. Showcase: build a thermometer node, then break it.
  10. Field guide: the bug table and the code.
The conveyor firmware checks the stop button between 500 ms LED delays. Why does a faster CPU not fix it?

Chapter 1

The Whole Computer on One Chip

Compare a microcontroller with a microprocessor board, and see what each part does

A microprocessor (MPU) is a fast CPU that needs other chips around it: external RAM, external storage, a power controller. A Raspberry Pi 4 is one: Cortex-A72 cores at 1.5 GHz, with 1 to 8 GB of separate RAM, booting Linux from an SD card in seconds.

A microcontroller (MCU) puts a smaller CPU, its program memory, its working memory and its peripherals on one chip. A peripheral is a hardware block that does one job next to the CPU: pins, timers, an analog converter, a serial port. Power it up and your code runs from on-chip flash within milliseconds.

Tap a block to see its job

The MCU view is one die: every block sits on the same chip. Switch to the MPU board and count the chips it needs. Tap any block.

Simplified layout, not a real die. MCU sizes are the STM32F103C8 datasheet's (64 KB flash, 20 KB SRAM, 72 MHz). The board is a generic MPU design.

Three real chips show the range. The STM32F103C8, a 72 MHz Cortex-M3, has 64 KB of flash and 20 KB of SRAM. The ATmega328P on an Arduino Uno has 32 KB of flash and 2 KB of SRAM, and runs at up to 20 MHz. The RP2040 bends the rule: two Cortex-M0+ cores and 264 KB of SRAM on chip, but its program flash sits in a separate chip on the board.

The small memory is the constraint you meet first. A 320 by 240 colour frame at 2 bytes per pixel is 153,600 bytes: 7.5 times the whole SRAM of the STM32F103C8. So an MCU does not hold a frame. It streams one, or it leaves the job to an MPU.

Choose by the job. Read a sensor and drive a relay every 10 ms, from power-on, on a coin cell: an MCU. Run a camera, a network stack and a user interface: an MPU with Linux (Embedded Linux is Lesson 5).

Symptom: you add a buffer, and the board resets or jumps to a fault handler.

Measure: open the linker's map file and add up the data, the zeroed data and the stack. Compare the sum with the SRAM size.

Fix: shrink or stream the buffer, or pick a part with more SRAM. The map file is taught in the firmware track.

Why does an MCU run its code milliseconds after power-on, while a Linux board takes seconds?

Chapter 2

Every Peripheral Is an Address

Find a register by adding an offset to a base, and set one bit to light an LED

On an MCU, the LED pin, the timer and the serial port all live in the same address space as memory. Writing to certain addresses does not store a number. It switches hardware. This is memory-mapped I/O, and each such address is a register.

The vendor's reference manual gives the memory map: which address range belongs to which block. On the STM32F103, flash starts at 0x0800_0000, SRAM at 0x2000_0000, and the peripherals from 0x4000_0000 up. Each peripheral has a base address, and its registers sit at fixed offsets from it.

Call the peripheral's base address B and the register's offset inside the block O. The register's address is A:

Say it aloud

A equals B plus O.

A
A the register's address: the number your code reads or writes.
B
B the base address of the peripheral, from the memory map. GPIOC starts at 0x4001_1000.
O
O the offset of one register inside the block, from the register table. The output data register, ODR, is at 0x0C.
In plain words

Look up the block's base B in the memory map. Look up the register's offset O in the block's register table. Add them. The sum A is where your pointer points.

With numbers

GPIOC's ODR: 0x4001_1000 + 0x0C = 0x4001_100C. Pin 13 is bit 13, so writing the mask 1 << 13 = 0x2000 there drives PC13 high.

Write bits to a port and watch the pins

Pick a port and a register. Tap bits to set or clear them. An LED hangs on pin PC13; it lights only when you write bit 13 of GPIOC.

Addresses and offsets from ST's RM0008 reference manual for the STM32F103. BSRR's upper half (reset bits) is left out of this toy.

In C you make a pointer to the address and mark it volatile. That word tells the compiler the value can change behind its back, so it must read or write the address every time. Without it, the compiler can turn a loop that waits on a register into a loop that never looks again.

c
#define GPIOC_ODR (*(volatile uint32_t *)0x4001100C)
GPIOC_ODR |=  (1u << 13);   // read, set bit 13, write back: PC13 high
GPIOC_ODR &= ~(1u << 13);   // read, clear bit 13, write back: PC13 low

Symptom: a wait loop on a status register works at -O0 and hangs at -O2.

Measure: read the disassembly. The load from the register sits outside the loop, so the loop tests a stale copy.

Fix: declare the register pointer volatile. Vendor headers do this for you.

GPIOB's base is 0x4001_0C00 and ODR's offset is 0x0C. Where do you write to drive GPIOB's output pins?

Chapter 3

A Pin Is a Switch You Configure

Turn on the port's clock, set the pin's mode, then drive an LED and read a button

GPIO (general-purpose input/output) pins are the metal pads where the chip meets the world. Each pin takes one of four modes. Input reads a voltage as 0 or 1. Output drives 3.3 V or 0 V. In alternate function, a peripheral such as a UART drives the pin; in analog, the ADC reads it.

A pin does nothing until two writes happen. First, turn on the port's clock. The MCU stops the clock to unused blocks to save power, and a block with no clock ignores writes. Second, set the mode bits. On the STM32F103, pin PA5 as a push-pull output takes 0b0011 in bits 23 to 20 of GPIOA's CRL register.

Bring up a pin, then light the LED

Do the three steps in any order and see which ones matter. Change the resistor and read the LED current. Hold the button to pull PA0 low.

Illustrative red LED with a 2.0 V forward drop. The 25 mA per-pin limit and the 30 to 50 kΩ internal pull-up are from the STM32F103x8 datasheet.

An output pin is a switch to 3.3 V, so Ohm's law sizes the LED resistor. The resistor takes what the LED leaves: 3.3 V minus the LED's 2.0 V forward drop is 1.3 V. Through 330 Ω that is 1.3 / 330 = 3.9 mA, a clear glow. Through 47 Ω it is 27.7 mA, over the pin's 25 mA rating.

An input needs a defined level when nothing drives it. A pull-up is a resistor to 3.3 V: the pin reads 1 when the button is open and 0 when the button shorts it to ground. That is active low: pressed reads 0. The STM32F103 has an internal pull-up of about 40 kΩ, so a held button costs 3.3 V / 40 kΩ = 83 µA.

c
RCC->APB2ENR |= (1u << 2);           // 1. clock to GPIOA
GPIOA->CRL &= ~(0xFu << 20);         // 2. clear PA5's four mode bits
GPIOA->CRL |=  (0x3u << 20);         //    output, push-pull, 50 MHz
GPIOA->ODR |=  (1u << 5);            // 3. PA5 high: LED on
int pressed = !(GPIOA->IDR & (1u << 0)); // PA0 reads 0 when pressed

Symptom: you write ODR and the LED stays dark. The debugger shows ODR still 0.

Measure: read RCC's enable register. If the port's bit is 0, the block has no clock and drops every write.

Fix: enable the clock first, then configure the mode, then drive the pin.

You write GPIOA->ODR, and nothing else, and the LED does not light. What did you forget?

Chapter 4

Count Ticks, Not Instructions

Set a timer's prescaler and reload value for an exact rate, then compare against it for PWM

The blink code waited with a loop that counts down a number. Its delay depends on the compiler, the optimisation level and the flash speed. A timer is a hardware counter that counts clock ticks instead. Its rate depends only on the clock and two numbers you write.

The first number is the prescaler, PSC: the timer counts once every PSC + 1 clock ticks. The second is the auto-reload value, ARR: the counter goes 0, 1, …, ARR, then wraps to 0 and raises an update event. Both have a +1, because each counts from zero.

Call the timer's input clock fclk. The update events come at the rate fupd:

Say it aloud

f-update equals f-clock divided by PSC plus one, times ARR plus one.

fupd
f-update how many times per second the counter wraps, in hertz.
fclk
f-clock the clock that feeds the timer, in hertz: 72 MHz here.
PSC
P-S-C the prescaler register: the counter moves once every PSC + 1 clock ticks. 16 bits, 0 to 65,535.
ARR
A-R-R the auto-reload register: the top count. One period is ARR + 1 counts.
In plain words

Divide the clock by PSC + 1 to get the counting rate. Divide again by ARR + 1, the counts in one period. What is left is f-update, the wraps per second.

With numbers

For 1 kHz from 72 MHz: PSC = 71 makes a 1 MHz count, and ARR = 999 makes 1,000 counts per period. 72,000,000 / (72 × 1,000) = 1,000 Hz, one update every millisecond.

Set the prescaler, the top and the compare

The yellow ramp is the counter, drawn over three periods. Each wrap is an update event. The purple line is the compare value; the blue trace is the PWM pin, high while the count is below it.

999
250

The ramp is drawn in slow motion; the read-out gives the real times. Timer behaviour (up-counting, PWM mode 1) as in RM0008.

A PWM (pulse-width modulation) output uses the same counter. A third register, the compare value CCR, splits each period: the pin is high while the count is below CCR and low after. Call the fraction of the period spent high the duty cycle, D:

Say it aloud

D equals CCR divided by ARR plus one.

D
D the duty cycle: the fraction of each period the pin is high, from 0 to 1.
CCR
C-C-R the capture/compare register: the count at which the pin goes low.
ARR
A-R-R the auto-reload value, as above. ARR + 1 is the counts in one period.
In plain words

The pin is high for CCR counts out of every ARR + 1. Divide one by the other to get D. An LED or a motor sees the average, D times 3.3 V.

With numbers

ARR = 999 and CCR = 250: D = 250 / 1,000 = 0.25. The pin is high 250 µs of every 1 ms, and the average is 0.25 × 3.3 = 0.83 V.

Symptom: a clock built on a 1 ms tick loses about a minute and a half per day.

Measure: someone wrote ARR = 1,000, not 999. The period is 1,001 counts: 999.0 Hz, an error of 999 ppm, 86.3 s per day.

Fix: write ARR = counts − 1 and PSC = divider − 1. Check the rate on a scope once.

You need a 500 Hz update from 72 MHz, with PSC = 71 (a 1 MHz count). What is ARR?

Chapter 5

Let the Hardware Call You

Follow one interrupt from the flag to the handler and back, and see why the handler must clear the flag

Polling means the code asks each peripheral, again and again, whether something happened. It answers only as fast as it asks. An interrupt turns this around. A peripheral raises a flag, and the CPU stops to run one function. Then it returns to the exact instruction it left.

That function is the interrupt service routine (ISR), or handler. On a Cortex-M the NVIC (nested vectored interrupt controller) decides which pending interrupt runs. "Vectored" means each source has its own entry in a table of handler addresses. "Nested" means a higher-priority interrupt can interrupt a lower-priority handler.

One interrupt, in order:

  1. The event sets a flag in the peripheral, for example TIM2's update flag.
  2. The CPU finishes or abandons its current instruction and pushes eight registers onto the stack: R0 to R3, R12, LR, PC and xPSR. That is 32 bytes.
  3. It reads the handler's address from the vector table and jumps there.
  4. The handler runs. It must clear the flag.
  5. On return, the CPU pops the eight registers and the old code continues.

Fire an interrupt and follow it

Warm bars are the CPU running code: main on the top lane, the handler below. Purple is the stack. Fire the interrupt. Then turn off "ISR clears the flag" and fire again.

Cycle counts: entry 12 cycles and tail-chaining 6 cycles on a Cortex-M3 with zero-wait-state memory (Arm). The 40-cycle handler and 12-cycle return are illustrative. Slow flash adds wait states to all of these.

Where is a handler's address? The table holds 16 system entries first (reset, faults, SysTick and others), 4 bytes each, then one per peripheral interrupt. TIM2 is interrupt number 28 on the STM32F103, so its entry sits at 4 × (16 + 28) = 176 = 0xB0 bytes into the table. With the table at the start of flash, that is 0x0800_00B0.

The entry takes 12 cycles on a Cortex-M3 with no flash wait states: 0.17 µs at 72 MHz. Compare that with a superloop that looks at a pin once every 20 ms.

c
volatile uint32_t ms = 0;          // shared with main: volatile
void TIM2_IRQHandler(void) {
    if (TIM2->SR & 1u) {            // update flag set?
        TIM2->SR &= ~1u;          // clear it, or the handler runs again at once
        ms++;                      // short: count, set a flag, leave
    }
}

Symptom: the board freezes. The debugger always stops inside the same handler.

Measure: look at the peripheral's status register on entry to the handler. If the flag is still set when the handler returns, the NVIC sees it pending and enters again.

Fix: clear the flag inside the handler, early. Keep handlers short: no delays, no printf, no waiting.

A timer handler runs, returns, and at once runs again, forever. Main never runs. What is the most likely cause?

Chapter 6

Turn a Voltage into a Number

Read a temperature sensor through a 12-bit ADC, and find where the resolution and the reference limit it

The world is analog. A temperature sensor such as the TMP36 outputs a voltage: 10 mV per degree Celsius, 750 mV at 25 °C, so 500 mV at 0 °C. The firmware wants a number. An ADC (analog-to-digital converter) compares the pin's voltage with a reference voltage and returns an integer code.

An N-bit ADC splits the range from 0 to the reference into 2N equal steps. The STM32F103's ADC has 12 bits: 4,096 steps. One step is the smallest voltage change the firmware can see.

Call the ADC's result the code, the reference voltage Vref and the number of bits N. The voltage the code stands for is V:

Say it aloud

V equals code times V-ref, divided by two to the N.

V
V the input voltage the code stands for, in volts (the bottom of its step).
code
code the integer the ADC returns, from 0 to 2N − 1.
Vref
V-ref the reference voltage: full scale. 3.3 V on this board.
2N
two to the N the number of steps. N = 12 bits gives 4,096.
In plain words

One step is V-ref divided by two to the N. Multiply the code by that step to get V. The firmware never sees a change smaller than one step.

With numbers

One step is 3.3 / 4,096 = 0.806 mV. At 22 °C the TMP36 gives 0.720 V, and the ADC returns 893. Back: 893 × 3.3 / 4,096 = 0.7195 V, so (0.7195 − 0.5) / 0.01 = 21.95 °C.

Read the sensor through the ADC

Drag the true temperature. Pink is the world, blue is the voltage on the pin, purple is the code and the temperature the firmware computes. Lower the bits, then let the reference sag.

22.0 °C

An ideal ADC with no noise. TMP36 scale (10 mV/°C, 750 mV at 25 °C) from the Analog Devices datasheet. The firmware always assumes V-ref = 3.3 V.

The old version of this page divided by 4,095. The ideal step is V-ref / 2N. Here the difference is 0.02 °C, far below the sensor's error, but V-ref / 2N is the right form.

The conversion takes time. On the STM32F103 it is a sampling time you choose plus 12.5 ADC clock cycles, about a microsecond. A timer can start each conversion, so the samples land at an even rate no matter how busy the CPU is (Timers, PWM and Sampling).

Symptom: every reading is about 2 °C high, more when the radio transmits.

Measure: probe V-ref. If it sags to 3.2 V while the code assumes 3.3 V, 0.720 V reads as 921 counts and 24.2 °C.

Fix: give the ADC a stable reference, or measure the chip's internal reference channel and scale by it.

A 10-bit ADC with a 3.3 V reference reads a TMP36. What is the smallest temperature change it can see?

Chapter 7

Talk to Other Chips: UART, SPI and I²C

Send one byte three ways, and trade wires against speed

The MCU shares the board with sensors, memories, displays and radios. Three serial buses carry most of that traffic. Each sends bits one after another on a few wires; they differ in who sets the timing and how the controller picks a chip.

BusWiresTimingChoosing a chipTypical rate
UARTTX, RXno clock; both sides agree a baud ratepoint to point9,600 to 115,200 baud and more
SPISCK, MOSI, MISO, one CS per chipthe controller drives a clockpull that chip's CS lowa few to tens of MHz
I²CSCL, SDA, sharedthe controller drives a clocka 7-bit address in the first byte100 kHz or 400 kHz, faster modes exist

A UART line idles high. Each byte, called a frame, starts with a low start bit, then 8 data bits, least significant first, then a high stop bit. That is the common "8N1" format: 10 bits on the wire for 8 bits of data.

How many bytes per second does a UART carry? Call the baud rate, the bits per second on the wire, b. With 10 bits per frame, the byte rate is RB:

Say it aloud

R-B equals b divided by ten.

RB
R-B the byte rate: data bytes per second.
b
b the baud rate: bits per second on the wire, start and stop bits included.
10
ten the bits in one 8N1 frame: 1 start, 8 data, 1 stop.
In plain words

Every data byte costs ten bit times on the wire. Divide the baud rate b by ten to get R-B, the bytes that get through each second.

With numbers

At 9,600 baud, R-B = 960 bytes per second. At 115,200 baud, 11,520 bytes per second, and one byte takes 10 / 115,200 = 86.8 µs.

Send 0x42 three ways

Pick a bus and watch the byte 0x42 (binary 0100 0010) go out bit by bit. Then add sensors and count the wires each bus needs.

8

Signal wires only; every bus also needs ground. On I²C, 0x42 is the address byte for address 0x21 with the write bit. SPI shown in mode 0, most significant bit first.

Count wires for 8 sensors. I²C uses 2 shared wires, since each sensor answers to its own address. SPI needs SCK, MOSI and MISO plus a chip-select per sensor: 11. The old page said I²C holds 127 devices; the spec reserves 16 of the 128 addresses, so 112 are usable.

Symptom: the serial console prints garbage characters.

Measure: scope the TX line and time one bit. At 115,200 baud it should be 8.68 µs. A different width means the two sides disagree on the baud rate or the clock behind it.

Fix: set both ends to the same rate, and compute the baud divider from the real peripheral clock (Chapter 4's APB note).

You must connect 8 temperature sensors with the fewest wires. Which bus?

Chapter 8

Superloop, Flags, State Machine, Sleep

Compute a superloop's worst response and a battery's life, then restructure until both pass

The simplest firmware is a superloop: one endless loop that calls every task in turn. It is easy to debug. But each task runs once per pass, so an event waits for the loop to come round.

Call the time each task takes Ci, for task i. If an event arrives just after its check, it waits one full pass. The worst-case response is Rmax:

Say it aloud

R-max equals the sum over i of C-i.

Rmax
R-max the longest an event can wait for its check in a superloop, in milliseconds.
Σi
the sum over i add one term for every task in the loop.
Ci
C-i the worst-case run time of task i, measured.
In plain words

Add up the worst time C-i of every task. The total is one pass. An event that just missed its check waits that long.

With numbers

With made-up tasks: sensors 2 ms, filtering 3 ms, display 12 ms, buttons 0.1 ms, serial 3 ms. R-max = 20.1 ms. A press that lands more than 10 ms before its check is late: 10.1 of every 20.1 ms, so 50% of presses.

Restructure the loop until it passes

The warm bars are one pass of the loop; the yellow line is the button's 10 ms deadline. Apply the three fixes one at a time and watch the response and the battery.

Illustrative task times and currents (10 mA awake, 0.05 mA asleep, a 2,000 mAh battery). With sleep on, the loop runs once per 100 ms timer tick, then the CPU sleeps.

In interrupt plus flags, each handler does the urgent part (cut the motor), sets a flag and returns. The loop does the slow part. A state machine keeps the slow part in order: the system is in one named state, and each event moves it to the next. Most firmware is both.

The loop can also sleep. The instruction WFI (wait for interrupt) stops the core until the next interrupt. Call the fraction of time awake the duty D, the current while running Irun and while asleep Isleep. The average current is Iavg:

Say it aloud

I-average equals D times I-run, plus one minus D, times I-sleep.

Iavg
I-average the average current drawn from the battery, in milliamps.
D
D the duty: the fraction of time the CPU is awake, from 0 to 1.
Irun
I-run the current while the CPU runs code.
Isleep
I-sleep the current while it sleeps.
In plain words

Weight the running current I-run by the time awake D, and the sleeping current I-sleep by the rest. Add them. Divide the battery's capacity by I-average to get its life.

With numbers

With made-up currents, 10 mA and 0.05 mA: a loop that never sleeps draws 10 mA, and 2,000 mAh lasts 200 h, 8.3 days. Awake 20.1 ms per 100 ms, D = 0.201: I-average = 2.05 mA, 40.7 days.

c
volatile uint8_t f_tick, f_button;              // one flag per source
void EXTI0_IRQHandler(void) { EXTI->PR = 1u; motor_off(); f_button = 1; }
void TIM2_IRQHandler(void)  { TIM2->SR &= ~1u; f_tick = 1; }
int main(void) {
    setup();
    for (;;) {
        if (f_button) { f_button = 0; state = STOPPED; }   // state machine step
        if (f_tick)   { f_tick = 0; sample(); update_display(state); }
        __WFI();                                  // sleep until the next interrupt
    }
}

Symptom: one button press in a few hundred is lost.

Measure: look for one flag word that main clears with flags &= ~BIT. That is a read, a change and a write; a handler that fires in between loses its bit.

Fix: one flag variable per source, as above, or mask interrupts around the read-modify-write.

The firmware must answer a button within 1 µs and also run 15 ms of filter maths. Which structure?

Chapter 9

Build the Thermometer Node, Then Break It

Run every part of this lesson together, then plant one classic bug at a time and watch the symptom

Here is the whole node. TIM2 wraps 10 times a second (PSC = 7,199, ARR = 999 at 72 MHz). Its handler starts an ADC conversion of the TMP36 and stores the code. Main converts the code to degrees and drives a display. A button on PA0 flips Celsius and Fahrenheit through an EXTI interrupt. Between ticks the core sleeps.

Run the node, plant a bug

The top shows the blocks and the value moving between them. The strip below is the last second of CPU time. Drag the temperature, press the unit button, then plant a bug.

22.0 °C

Illustrative timing: handler 0.05 ms, conversion and maths 0.5 ms, a 12 ms display update per tick; currents as in Chapter 8. Each bug shows the symptom that bug has on real hardware.

Each bug is one line, and each looks like a different fault. A flag left set freezes everything. A missing volatile freezes only the display, while the handlers keep running. An ADC with no clock never converts, so the display shows −50.0 °C, the reading for 0 V. A handler that waited for that conversion would wait forever. A slow display inside a handler delays the button by up to 12 ms. Find each one by its symptom, not by reading every line.

c
volatile uint16_t adc_value;  volatile uint8_t new_sample, use_f;
void TIM2_IRQHandler(void) {          // 10 Hz: PSC 7199, ARR 999
    TIM2->SR &= ~1u;
    adc_value = ADC1->DR;                // result of the conversion started last tick
    ADC1->CR2 |= 1u;                    // start the next one; do not wait here
    new_sample = 1;
}
void EXTI0_IRQHandler(void) { EXTI->PR = 1u; use_f ^= 1; }
// main: if (new_sample) { new_sample = 0;
//   float c = (adc_value * 3.3f / 4096.0f - 0.5f) * 100.0f;
//   show(use_f ? c * 9 / 5 + 32 : c); }  __WFI();

The old page's handler started a conversion and then waited for it inside the handler. Reading last tick's result and starting the next conversion removes the wait.

Chapter 10

Field Guide

Keep the numbers, the bug table and the next steps in one place

An MCU is a CPU, memory and peripherals on one chip. Every peripheral is a set of registers at a base plus an offset. Pins need a clock and a mode. Timers count hardware ticks; interrupts let those ticks, and the world, call your code within cycles. Structure the firmware so the urgent part runs in a short handler, the slow part runs in the loop, and the core sleeps when it can. Then check the worst case against the deadline.

QuantityRuleExample
Cycle budgetN = f T72 MHz × 1 ms = 72,000
Register addressA = B + O0x4001_1000 + 0x0C = 0x4001_100C
Timer ratefclk / ((PSC + 1)(ARR + 1))72 MHz / (72 × 1,000) = 1 kHz
PWM dutyCCR / (ARR + 1)250 / 1,000 = 25%
Vector entry4 × (16 + IRQ number)TIM2: 0xB0
ADC voltagecode × Vref / 2N893 → 0.7195 V → 21.95 °C
UART bytesbaud / 10115,200 → 11,520 B/s
Superloop responseRmax = Σ Ci20.1 ms
Average currentD Irun + (1 − D) Isleep2.05 mA → 40.7 days
BugSymptomWhat names it
Peripheral clock offwrites do nothingRCC enable bit is 0
Missing volatileworks at -O0, hangs at -O2the load sits outside the loop
ARR off by oneclock drifts 86 s a dayperiod is ARR + 1 counts
Flag not clearedfrozen, always in one handlerflag still set on return
Waiting in a handlerother interrupts late, or a hanga while loop inside an ISR
Shared flag wordrare lost eventsread-modify-write in main
Reference sagreadings shift with loadV-ref below its assumed value
Baud mismatchgarbage on the consolebit width on the scope
Long superlooplate answers, about half the timepin toggle shows a 20 ms pass
python
def timer_rate(f_clk, psc, arr):
    return f_clk / ((psc + 1) * (arr + 1))

def find_psc_arr(f_clk, f_want, max16=65535):
    """Smallest prescaler that lets ARR fit in 16 bits; exact when it divides."""
    total = round(f_clk / f_want)              # (PSC + 1)(ARR + 1)
    for div in range(1, max16 + 2):
        if total % div == 0 and total // div <= max16 + 1:
            return div - 1, total // div - 1
    return None

def vector_offset(irq):
    return 4 * (16 + irq)                    # 16 system entries come first

def adc_to_celsius(code, vref=3.3, bits=12):
    v = code * vref / 2 ** bits
    return (v - 0.5) / 0.01                   # TMP36: 10 mV per degree, 0.5 V at 0 C

def battery_days(duty, i_run_ma, i_sleep_ma, cap_mah):
    i_avg = duty * i_run_ma + (1 - duty) * i_sleep_ma
    return cap_mah / i_avg / 24

We ran each function. timer_rate(72e6, 71, 999) is 1000.0 and find_psc_arr(72e6, 1000) is (1, 35999). vector_offset(28) is 176, adc_to_celsius(893) is 21.95, and battery_days(0.201, 10, 0.05, 2000) is 40.7.

Where it sits. Past a handful of tasks, a superloop gives way to a real-time operating system, which runs each task in its own thread with a priority. A Linux board takes over when the job needs a network stack, a file system or a screen. The registers, interrupts and deadlines underneath do not change.

Keep going

Read next

The habit. For every event, ask who notices it and how soon. If the answer is "the loop, eventually", give it an interrupt, measure the worst case, and let the core sleep the rest of the time.
A superloop's pass is 20.1 ms and the button deadline is 10 ms. Which single change makes every press on time?

Now teach it: press Present or Teach and explain why a 20.1 ms superloop misses a 10 ms deadline half the time, and what an interrupt changes. Then go back to the stop button and predict the miss rate at 30 ms of work before you drag.

Embedded Systems · Lesson 1: From Blinking LEDs to Real-Time Control
Next: Embedded C · Back to Gleams