An STM32F103C8 has 20 KB of SRAM, and every global, buffer and stack frame you write comes out of it. A 2,048-byte table without const takes 2,048 bytes of that SRAM. With const it stays in flash and takes none.
Pick how you declare the table, then drag the stack deeper. Watch the free gap close, and see what the stack overwrites when it runs out. Then we build, piece by piece, the types, bits, memory, interrupts, numbers, clocks, DMA and watchdog that firmware is made of.
You need a little C and binary and hex numbers. Lesson 1 helps. We build the rest from zero.
Lesson 2 of the Embedded Systems series. Before: Lesson 1, Embedded Systems. Next: Lesson 3, Hardware Design. The hands-on track is Firmware from Zero.
Illustrative firmware: 21 KB of code, 64 B of other initialised globals, 3,712 B of zeroed buffers (a 1,024 B display frame, a 2,048 B ADC buffer, a 256 B UART ring, 384 B of other state), no heap. The 64 KB flash and 20 KB SRAM are the STM32F103C8 datasheet's. The section sizes match what clang reports for these declarations on a Cortex-M3 target.
Chapter 0
See four bugs that are legal C, and follow one call down the layers to a pin
A sensor node passes every bench test. In the field it fails four ways.
After seven weeks, a timeout fires at once. At 115,200 baud, the console loses bytes. A build with -O2 skips a wait. A new lookup table makes it reset. Every line is legal C.
Each bug comes from a fact that C does not show you: how wide a type is, where a variable lives, who else writes it, and when a number wraps. On a laptop, the operating system and a large memory hide most of these facts. On a microcontroller, nothing runs under main() except the code you and the startup file put there.
So firmware comes in layers. The application decides what to do. A driver knows one device, such as a display or a sensor. The HAL (hardware abstraction layer) is a set of functions that wrap register writes, so the code above never names an address. Only the bottom layer touches registers.
Press Send and watch the call travel down. Then switch the chip and send again: only the bottom rows change. Tap a layer to read what it knows.
Addresses from ST's reference manuals: RM0008 (STM32F103) and RM0090 (STM32F407). HAL_GPIO_WritePin is ST's HAL call, which writes the port's BSRR register. The driver and application names are made up.
The same LED write lands at two different addresses. On the STM32F103, GPIOA's bit set/reset register, BSRR, sits at 0x4001_0800 + 0x10 = 0x4001_0810. On the STM32F407 it sits at 0x4002_0000 + 0x18 = 0x4002_0018. The HAL hides the difference, so the application calls the same function on both chips.
Symptom: moving to a new chip means edits in fifty files.
Measure: search the application code for register names and raw addresses.
Fix: move every register access down into the driver or the HAL. The drivers step of the firmware track builds one.
Chapter 1
Use types with a known width, then write one field of a register and leave its neighbours alone
In C, int is not a size. The standard only says an int holds at least −32,767 to 32,767, so 16 bits is enough. On a Cortex-M an int is 32 bits. On an 8-bit AVR it is 16. A long is 4 bytes on a Cortex-M and 8 bytes on a 64-bit Mac.
A register has an exact width, so firmware uses the fixed-width types from <stdint.h>: uint8_t, int16_t, uint32_t. Each one has exactly the bits its name says. The u means unsigned.
Four operations do most of the work. Set bit n with R |= 1u << n. Clear it with R &= ~(1u << n). Toggle it with ^=, and test it with (R >> n) & 1u. Write the u: 1 << 31 shifts a signed int past its top bit, which C leaves undefined.
A field is a group of bits that act as one number. On the STM32F103, pin PA5's mode is the 4-bit field at bits 23 to 20 of GPIOA's CRL register. The other 28 bits configure seven other pins. A write to PA5 must leave them alone.
Pick a pin and the 4-bit value for it, then press Write. The rows show each step. Switch on "plain =" to see what a careless assignment does to the other pins.
CRL's reset value 0x4444_4444 and the meaning of each 4-bit code are from ST's RM0008, section 9.2.1. The register starts from its reset value each time.
How do you write a field? Call the register's old value R. Call the field's mask, all ones and as wide as the field, m. Call the field's lowest bit position, the shift, s. Call the new field value v. The new register value is R′:
R-prime equals R and not m shifted left by s, or v shifted left by s.
Shift the mask m up to bit s and invert it. AND it with R: that clears the field and keeps every other bit. Shift v up to bit s and OR it in. Write R-prime back.
R = 0x4444_4444, m = 0xF, s = 20, v = 0x3. m << s = 0x00F0_0000. R & ~0x00F0_0000 = 0x4404_4444. OR 0x0030_0000 gives R′ = 0x4434_4444. PA5 is now an output; the other seven pins keep 0x4, floating input.
Vendor headers describe each peripheral as a struct laid over its base address. The members sit 4 bytes apart in register order, so GPIOA->ODR is the base plus 0x0C.
c typedef struct { volatile uint32_t CRL, CRH, IDR, ODR, BSRR, BRR, LCKR; } GPIO_TypeDef; #define GPIOA ((GPIO_TypeDef *)0x40010800u) // ODR lands at +0x0C, BSRR at +0x10 uint32_t r = GPIOA->CRL; // read once r = (r & ~(0xFu << 20)) | (0x3u << 20); // clear PA5's field, insert 0x3 GPIOA->CRL = r; // write once
Symptom: you set PA5 as an output and the button on PA0 stops working.
Measure: read CRL before and after the write and compare every 4-bit field.
Fix: clear the field with its mask, then OR in the value. GPIOA->CRL = 0x3u << 20 sets the other seven fields to 0x0, analog mode.
Chapter 2
Place each kind of variable in flash or SRAM, and step the code that runs before main
Where a variable lives depends on how you declare it. The linker is the build tool that gives every piece of code and data an address. It sorts them into sections, named groups with one rule each:
| You write | Section | Lives in | Who sets its first value |
|---|---|---|---|
| the code of every function | .text | flash | the programmer that flashed the chip |
const int16_t sine[1024] = {…}; | .rodata | flash | the programmer that flashed the chip |
int counter = 42; | .data | SRAM, with its 42 kept in flash | the startup code copies it |
static uint8_t fb[1024]; | .bss | SRAM | the startup code writes zeros |
char line[80]; inside a function | the stack | SRAM | nobody: garbage until you write it |
malloc(256) | the heap | SRAM | nobody |
Before main, a short program runs. At reset, a Cortex-M reads two words from the vector table, a table of addresses at address 0, where the STM32 maps the start of flash. Word 0 is the starting stack pointer. Word 1 is the address of the reset handler. The reset handler copies .data from flash to SRAM, zeroes .bss, sets up the clock, and calls main.
Press Step to run one stage of the reset sequence. Pick a variable to see where it lives and what it holds at each stage.
Illustrative sizes from the hero's firmware. The two vector words, the .data copy and the .bss zeroing follow Arm's ARMv7-M reset behaviour and the usual GCC startup file. The reset handler's address 0x0800_0145 is made up; its last bit is 1 because a Cortex-M runs only Thumb code.
The zeroing is not decoration. The C standard says a global with no initialiser starts at zero. On a laptop the operating system makes that true. On a microcontroller, the reset handler's .bss loop makes it true.
How much SRAM does the firmware need? Call the size of .data Sdata, of .bss Sbss, of the heap Sheap, and the deepest the stack ever goes Sstack. The chip has SRAM bytes:
S-data plus S-bss plus S-heap plus S-stack is at most S-RAM.
Read S-data and S-bss from the linker's map file. Add the heap you reserve and the deepest stack you measured. If the total is more than S-RAM, something gets overwritten.
The hero's firmware with the table not const: 2,112 + 3,712 + 0 + 12,288 = 18,112 B, under 20,480 B, with 2,368 B to spare. Make the table const and S-data falls to 64 B, so the spare grows to 4,416 B.
Symptom: after a deep call, the display shows a stripe of garbage and nothing crashes.
Measure: fill the stack with a known pattern at reset, run the worst case, then find the lowest address where the pattern is gone.
Fix: give the stack more room, move big locals to static buffers, or set an MPU guard region. The stack and MPU step does all three.
Chapter 3
Move a table out of SRAM with one word, then size it for the error you can accept
A sine table never changes. Declare it const and the linker puts it in .rodata, in flash. Leave out const and it goes to .data: its values sit in flash, a copy sits in SRAM, and the reset handler copies it at every boot.
We compiled both forms with clang for a Cortex-M3. With const, the 1,024-entry int16_t table made 2,048 bytes of .rodata. Without it, the same table made 2,048 bytes of .data. That is 10% of the STM32F103C8's SRAM, spent on numbers that never change.
Why keep a table at all? A Cortex-M3 has no floating-point unit, so sinf() runs as a software routine of many instructions. A table answers with one load. You trade flash for cycles, and the table's size decides its error.
How big must it be? Call the number of entries over one full turn n. Entries sit 2π/n radians apart, so the nearest entry is at most π/n away. The sine never changes faster than 1 per radian, so its value is off by at most that much. Call the worst error emax:
e-max is about pi over n.
Double the entries n and the worst error e-max halves. Each entry costs 2 bytes in Q15, a format Chapter 5 explains. So decide the error first, then pay for the n it needs.
n = 256: e-max = 3.1416 / 256 = 0.0123, for 512 bytes of flash. n = 1,024: 0.0031, for 2,048 bytes. Our script measured 0.01226 and 0.00307.
The pink curve is the true sine; the purple steps are what the table returns. Drag the entries and read the error and the bytes. Then switch on linear interpolation between two entries.
Errors measured by sampling one turn at 200,000 points, as in our check script. Entries are 2-byte Q15 values: round(32,767 × sin(2πk/n)). The 20,480-byte SRAM and 65,536-byte flash are the STM32F103C8's.
Linear interpolation draws a straight line between two neighbours. Its worst error is (2π/n)2/8, so 256 entries give 0.000075, better than 16,384 entries with the nearest-entry lookup.
c static const int16_t sine[256] = { 0, 804, 1608, 2410, /* ... */ }; // .rodata: flash only int16_t fast_sin(uint8_t phase) { return sine[phase]; } // phase 0..255 is one turn
Symptom: SRAM is nearly full, though most of the big arrays never change.
Measure: open the map file and look for the tables under .data instead of .rodata.
Fix: declare them static const. The map file step shows how to read the sections.
const from a 2,048-byte table. What changes?Chapter 4
Follow three rules for shared variables, then size a ring buffer for the longest gap
An interrupt handler can run between any two instructions of main. Any variable they share needs three rules.
while (!*p) {} for a Cortex-M3 at -O2. Without volatile, clang deleted the loop and the function returned at once. With volatile, it loaded the flag on every pass.count++ is a load, an add and a store. A handler that runs between them loses its own update. A Cortex-M reads and writes an aligned 8-, 16- or 32-bit value in one access, but a 64-bit value takes two.printf. Copy the data, set a flag, return.A ring buffer follows all three. The UART handler writes each byte at index head. Main reads from index tail. Each index has one writer, so it needs no lock. The buffer only has to hold the bytes that arrive while main is busy elsewhere.
Bytes arrive in blue; main drains the ring each time it comes back. Drag how long main stays away. Change the baud rate and the ring size, and watch for dropped bytes.
Illustrative: a steady stream of bytes, 10 bits each (start, 8 data, stop), and a main loop that drains the whole ring each time it returns.
How big must the ring be? Call the baud rate, in bits per second, b. Each byte costs 10 bits on the wire. Call the longest time main stays away tgap. The ring size N must satisfy:
N is at least b over ten, times t-gap.
Divide b by 10 to get bytes per second. Multiply by t-gap to get the bytes that pile up while main is away. N must hold all of them.
b = 115,200 gives 11,520 bytes per second. A 20 ms gap piles up 230.4 bytes, so a 256-byte ring holds. A 30 ms gap piles up 345.6, so about 90 bytes drop every pass.
The handler has a deadline too. The STM32F103's USART holds one received byte. At 115,200 baud the next byte lands 86.8 µs later. If the handler has not read the first byte by then, the overrun flag sets and a byte is lost.
c #define N 256u // a power of two, so i & (N - 1) wraps the index static volatile uint8_t buf[N]; static volatile uint16_t head, tail; // free-running; the ISR writes head, main writes tail void USART1_IRQHandler(void) { uint8_t c = USART1->DR; // reading DR clears the receive flag if ((uint16_t)(head - tail) < N) { buf[head & (N - 1)] = c; head++; } // else: full, drop } uint16_t rx_count(void) { return (uint16_t)(head - tail); } // 0 to N, and N means full
Symptom: the ring loses 256 bytes at once, only when it fills up.
Measure: read the count code. (head - tail) & (N - 1) gives 0 for a full ring, so the full ring looks empty.
Fix: keep the indices free-running and compute the count as (uint16_t)(head - tail), which runs from 0 to N.
Chapter 5
Know which integers wrap and which break, then store fractions in integers
An unsigned integer wraps by rule: a uint32_t that passes 4,294,967,295 goes back to 0. A signed integer that overflows is undefined behaviour: the standard sets no result, and the optimiser may assume it never happens.
Wraparound bites every millisecond counter. A uint32_t tick wraps after 232 ms, which is 49.7 days. Write timeouts as now - start >= timeout. The subtraction wraps too, so the answer stays right. The form now >= start + timeout fails near the wrap.
Take start = 4,294,967,000, about 0.3 s before the wrap, and a 1,000 ms timeout. Then start + timeout wraps to 704, and now >= 704 is true at once. With the subtraction, at now = 704 after the wrap, now − start = 1,000: on time.
C also widens small types before arithmetic. Two uint8_t values, 200 and 100, add as an int to 300; stored back in a uint8_t, the sum is 44. We checked each result with a C compiler.
Many Cortex-M chips have no floating-point unit, so firmware stores fractions in integers: fixed point. You pick how many bits hold the fraction. Call that count Q, the real number x, and the integer you store X:
X equals round of x times two to the Q.
Multiply x by 2 to the Q and round it: that is X. To read it back, divide X by 2 to the Q. The step between two values is 1 over 2 to the Q.
x = 0.1, Q = 15: 0.1 × 32,768 = 3,276.8, so X = 3,277. Read back, 3,277 / 32,768 = 0.100006, off by 0.000006.
To multiply two fixed-point numbers A and B, multiply the integers, then shift right by Q to remove one copy of the scale. The full product needs twice the bits. In Q16.16 (16 integer bits, 16 fraction bits), 1.5 is 98,304 and 2.25 is 147,456:
98,304 × 147,456 = 14,495,514,624 (a 64-bit product); >> 16 = 221,184 = 3.375
Kept in 32 bits, the product wraps to 1,610,612,736 and the answer comes out as 0.375. Cast to int64_t before you multiply.
Drag the fraction bits Q and the number x. Fewer integer bits give finer steps and a smaller range. Then square x with a 32-bit and with a 64-bit product.
Exact integer arithmetic (BigInt) on a signed 32-bit word, rounding to nearest and an arithmetic right shift, as GCC does on Cortex-M.
Symptom: a filter works for small inputs, then flips sign for large ones.
Measure: log the product before the shift and compare it with a floating-point model on a PC.
Fix: widen to int64_t before the multiply, and saturate the result to the type's range.
Chapter 6
Multiply a crystal up with the PLL, keep every branch inside its limit, and slow flash down to match
A chip starts on its internal oscillator, an RC circuit on the die. It needs no parts, but ST rates it at about 1% accuracy at room temperature. A UART or USB link needs better. A crystal on the board is accurate to tens of parts per million, but it runs at only 8 MHz or so.
The PLL (phase-locked loop) fixes that. It divides the crystal down to a small reference and multiplies that up inside a fast oscillator, the VCO. A last divider gives the CPU clock, SYSCLK. On the STM32F407 the three numbers are M, N and P.
Call the crystal frequency fHSE, the input divider M, the multiplier N, and the output divider P. The CPU clock is fSYS:
f-SYS equals f-HSE times N, over M times P.
Divide f-HSE by M to get a 1 to 2 MHz reference. Multiply by N to get the VCO, which must be 100 to 432 MHz. Divide by P to get f-SYS.
f-HSE = 8 MHz, M = 8, N = 336, P = 2: 8 / 8 = 1 MHz, times 336 = 336 MHz, over 2 = 168 MHz. A fourth divider, Q = 7, gives 336 / 7 = 48 MHz for USB.
Drag M and N and pick P. Each box shows its frequency and turns red when it leaves its limit. The flash wait states follow the CPU clock.
Limits from ST's RM0090 for the STM32F407: PLL input 1 to 2 MHz, VCO 100 to 432 MHz, SYSCLK up to 168 MHz, APB1 up to 42 MHz, APB2 up to 84 MHz, USB at 48 MHz, and one flash wait state per 30 MHz at 2.7 to 3.6 V. M is capped at 16 here to keep the slider usable.
Flash cannot keep up with a fast CPU. On the STM32F407 at 3.3 V, each 30 MHz of clock needs one more wait state, an extra cycle per flash read. At 168 MHz that is 5. The series' STM32F103 is simpler: 8 MHz × 9 = 72 MHz, 2 wait states, and APB1 divided by 2 to stay at 36 MHz.
Symptom: the board hard-faults or runs wild the moment the clock switches to the PLL.
Measure: check the order of the writes. If the flash latency is still 0 when SYSCLK jumps, the CPU reads flash faster than flash can answer.
Fix: raise the flash latency first, then switch to the PLL. To slow down, switch first, then lower the latency.
Chapter 7
Hand the copying to hardware, then process one half of the buffer while DMA fills the other
An ADC sampling at 10 kHz makes a number every 100 µs. With the CPU doing the copy, it must stop 10,000 times a second to move one value. DMA (direct memory access) is a hardware block that copies data between a peripheral and memory on its own. You give it a source, a destination and a count. It raises an interrupt when it finishes.
Two flags decide where the data goes. The ADC's data register stays at one address, so the peripheral address must not increment. The buffer moves on, so the memory address must. Swap them and every sample lands in one slot.
In circular mode, DMA starts again at the top of the buffer when the count reaches zero. It also raises a half-transfer interrupt in the middle. So you process the first half while DMA fills the second, and the second half while it fills the first. This is double buffering.
The blue head is DMA writing samples. When a half fills, the CPU starts on it (warm bar). Drag the processing time past the yellow half-buffer line and watch DMA catch the CPU.
Illustrative: a 1,024-sample buffer and a fixed processing time per half. Time on screen is slowed so one buffer takes about 3 s.
How long can processing take? Call the buffer length in samples N and the sample rate fs. Half the buffer fills in thalf. Your processing time tproc must fit inside it:
t-half equals N over two, over f-s, and must be at least t-proc.
Halve N and divide by f-s: that is t-half, the time before DMA comes back to the half you are reading. Your worst t-proc must be shorter.
N = 1,024 and f-s = 10 kHz: 512 / 10,000 = 51.2 ms per half. At 48 kHz it is 10.7 ms, so a 30 ms filter that fits at 10 kHz fails at 48 kHz.
The same idea sends data out. A 128 by 64 monochrome display frame is 1,024 bytes. Over SPI at 21 MHz, DMA sends it in 390 µs while the CPU draws the next frame.
c static volatile uint16_t adc_buf[1024]; // DMA writes here in circular mode void DMA1_Channel1_IRQHandler(void) { // ADC1 on STM32F103 if (DMA1->ISR & DMA_ISR_HTIF1) { DMA1->IFCR = DMA_IFCR_CHTIF1; half_ready = 1; } // first half full if (DMA1->ISR & DMA_ISR_TCIF1) { DMA1->IFCR = DMA_IFCR_CTCIF1; half_ready = 2; } // second half full }
Symptom: clicks in audio, or spikes in sensor data, that come and go with load.
Measure: set a pin high while processing a half and low after. Compare the pulse width with t-half on a logic analyser.
Fix: make the buffer longer, or the processing shorter. The DMA ping-pong lesson does this for audio.
Chapter 8
Let a hardware timer reset a stuck chip, and read what went wrong after a fault
A node on a roof has no one to press reset. The independent watchdog (IWDG) is a counter with its own clock that counts down. The firmware must reload it, or kick it, before it reaches zero. If the code hangs, no kick comes, the count hits zero, and the watchdog resets the chip.
Once started, nothing can stop the IWDG, by design: a bug must not turn off the guard. It runs on the LSI, a slow internal RC oscillator. The datasheet allows the STM32F103's LSI anywhere from 30 to 60 kHz, so the timeout moves with it.
Call the prescaler's divider d (4, 8, 16 and so on up to 256), the reload value RLR, and the LSI frequency fLSI. The time from a kick to a reset is tWD:
t-W-D equals d times RLR plus one, over f-L-S-I.
Multiply d by RLR + 1 to get the LSI ticks to zero. Divide by f-LSI to get seconds. Do it again with the slowest and the fastest LSI to get the window.
PR = 4 gives d = 64. RLR = 2,499. At 40 kHz: 64 × 2,500 / 40,000 = 4.0 s. At 60 kHz the timeout is 2.67 s, so kick at least every 2.67 s, not every 4.
The yellow saw is the watchdog count; each warm tick is a kick from the main loop. Drag the kick period, pick the LSI, then switch on the hang at 6 s.
PR = 4 and RLR = 2,499 as in the worked example. The LSI range is the STM32F103x8 datasheet's. After a reset the chip runs the Chapter 2 sequence; here the reboot takes an illustrative 0.3 s.
Kick in one place: at the end of the main loop, after every task ran. A kick inside a timer interrupt keeps coming while main is stuck, so the watchdog never fires.
Some bugs stop the CPU instead. A HardFault is the exception a Cortex-M takes for an error it cannot handle another way. Its fault status register, CFSR at 0xE000_ED28, says which error. Two common beliefs are wrong on a Cortex-M3:
| You expect a fault from | What a Cortex-M3 does |
|---|---|
| reading through a NULL pointer | An STM32 that boots from flash mirrors flash at address 0, so the read returns the first vector-table word. No fault. |
| dividing an integer by zero | The divide instruction returns 0, unless you set the DIV_0_TRP bit in the CCR register. |
| the stack running into .bss | No fault without an MPU guard (Chapter 2). |
| jumping to an address with no code | A fault: the CFSR shows which kind. |
Symptom: the main loop is frozen, but the watchdog never resets the chip.
Measure: search for the kick. If it sits in a timer handler, it runs whatever main does.
Fix: kick only from the main loop, after every task finished. The fail-safe lesson goes further.
Chapter 9
Budget a node's charge one phase at a time, then plant three one-line bugs and watch the battery life fall
Here is the whole design. An STM32L476, a low-power Cortex-M4, reads a BME280 (temperature, humidity and pressure) over I²C. It sends 12 bytes over an SX1276 LoRa radio on SPI every 5 minutes. A 3,000 mAh cell powers it. Between readings the chip sits in Stop mode: the clocks stop, SRAM keeps its contents, and the real-time clock wakes it.
Each cycle has four phases: wake and restore the clock, read the sensor, send, sleep. Call each phase's time ti and current Ii, the cycle period T, and the battery's capacity C. The average current is Iavg:
I-average equals the sum over i of t-i times I-i, over T.
Multiply each phase's time t-i by its current I-i to get its charge. Add the charges and divide by T. The battery lasts C divided by I-average.
Illustrative currents: 5 ms at 10 mA, 50 ms at 5 mA, 100 ms at 120 mA, and 299.845 s at 2 µA. That is 3.583 µAh per cycle. Over 300 s, I-average = 43.0 µA, so 3,000 mAh lasts 69,800 h, 7.96 years.
The top strip is one cycle, on a log scale of current. The bars are the charge each phase costs. Drag the reading interval, then plant one bug at a time.
Illustrative currents and times, the old lesson's design: wake 5 ms at 10 mA, sense 50 ms at 5 mA, LoRa send 100 ms at 120 mA, Stop 2 µA. Radio standby is an illustrative 1.6 mA. Battery life ignores the cell's self-discharge and temperature.
The send phase is 3.333 of the 3.583 µAh, 93% of the charge. So the send time and the interval decide the life. At 30 minutes the model gives 38.7 years, which means the cell's own self-discharge sets the limit, and this model leaves that out. Each bug below is one line, and each costs years.
HAL_Delay(300000) keeps the core awake at 10 mA: 12.5 days.c while (1) { bme280_read(&pkt); // sense: I2C, forced mode sx1276_send(&pkt, sizeof pkt); // send: 12 bytes; the DIO0 interrupt marks the end while (!tx_done) __WFI(); // sleep until the send ends, do not spin tx_done = 0; sx1276_sleep(); // the line the first bug forgets iwdg_kick(); enter_stop(300); // RTC wakes us; IWDG frozen by its option bit clock_restore(); // Stop turned the PLL off }
Chapter 10
Keep the rules, the numbers and the bug table in one place
Use types with a known width and write fields through a mask. Know which section each variable lands in, and keep the sum under the SRAM. Put tables in flash with const. Share data with interrupts through volatile, one writer per variable, and short handlers. Let unsigned counters wrap, keep signed ones in range, and widen fixed-point products. Set the clock tree inside its limits, let DMA move the bytes, kick the watchdog from the main loop, and budget every phase's charge.
| Quantity | Rule | Example |
|---|---|---|
| Field write | (R & ~(m << s)) | (v << s) | 0x4444_4444 → 0x4434_4444 |
| SRAM budget | data + bss + heap + stack ≤ RAM | 18,112 ≤ 20,480 B |
| Table error | π / n | n = 256: 0.0123, 512 B |
| Ring size | (b / 10) · tgap | 115,200, 20 ms: 230.4 B |
| Tick wrap | 232 ms | 49.7 days |
| Fixed point | round(x · 2Q) | 0.1 in Q15: 3,277 |
| PLL | fHSE · N / (M · P) | 8 · 336 / (8 · 2) = 168 MHz |
| DMA half time | (N / 2) / fs | 512 / 10 kHz = 51.2 ms |
| Watchdog | d (RLR + 1) / fLSI | 64 · 2,500 / 40 kHz = 4.0 s |
| Average current | Σ ti Ii / T | 43.0 µA → 7.96 years |
| Bug | Symptom | What names it |
|---|---|---|
| Register written with = | another pin stops working | the other fields changed |
| Stack too small | globals turn to garbage, no fault | the stack pattern is gone |
| Table without const | SRAM full | the table sits in .data |
| Missing volatile | a wait loop vanishes or spins at -O2 | no load inside the loop |
| Ring count with a mask | a full ring reads as empty | (head − tail) & (N − 1) |
| start + timeout | a timeout fires at once after 49.7 days | the sum wrapped |
| 32-bit fixed-point product | sign flips for large values | the product overflows |
| PLL before wait states | fault at the clock switch | flash latency still 0 |
| Kick in a timer ISR | frozen, never reset | the kick's location |
| Watchdog not frozen in Stop | resets every 8 s | IWDGRSTF set at each boot |
python def field_write(r, mask, shift, v): return (r & ~(mask << shift) & 0xFFFFFFFF) | ((v & mask) << shift) def ring_size(baud, gap_s): need = baud / 10 * gap_s n = 1 while n < need: n *= 2 # next power of two return n def to_fixed(x, q): return round(x * 2 ** q) def fixed_mul(a, b, q): return (a * b) >> q # Python ints are wide, like int64_t def pll(f_hse, m, n, p): return f_hse / m * n / p def iwdg_timeout(pr, rlr, f_lsi): return 4 * 2 ** pr * (rlr + 1) / f_lsi def battery_years(phases, period_s, cap_mah): i_avg = sum(t * i for t, i in phases) / period_s # mA return cap_mah / i_avg / 24 / 365.25
We ran each function. field_write(0x44444444, 0xF, 20, 3) is 0x44344444. ring_size(115200, 0.04) is 512. fixed_mul(98304, 147456, 16) is 221184, which is 3.375. pll(8, 8, 336, 2) is 168.0 and iwdg_timeout(4, 2499, 40000) is 4.0. battery_years([(0.005, 10), (0.05, 5), (0.1, 120), (299.845, 0.002)], 300, 3000) is 7.96.
Where it sits. Past a few tasks, a real-time operating system gives each task its own stack and priority, and every rule here still holds inside each task. Rust for firmware moves some of these checks into the compiler. The memory map, the clock tree and the watchdog stay the same.
Now teach it: press Present or Teach and explain why removing const from a table costs SRAM but no flash, and why the stack can overwrite a global without a fault. Then go back to the memory bars and predict the free gap with a float table and a 12 KB stack before you drag.