Bits, Bytes and the Memory Map

An accelerometer sends two bytes, 0xFF then 0x9C. Read them in one order and the board sits still at −0.006 g. Read them in the other and it claims −1.55 g.

Learn how firmware sees memory: single bits, fixed-size integers, byte order, padding, alignment and the addresses where the hardware itself lives.

Flip the byte order, then drag the true reading. Watch the same two bytes mean two different things. Then we build, piece by piece, the five ideas under it: bit masks, integer widths, endianness, alignment and the memory map.

You need a little C (variables, arrays, pointers) and the idea that a byte is eight bits. We build the rest from zero.

Step 1 of the Firmware from Zero series. Grounded on primary sources: the Arm Procedure Call Standard (AAPCS32), the STMicroelectronics CMSIS device header for the STM32F401xE, Arm’s Cortex-M user guides, and Memfault’s Interrupt post “The Hidden Cost of Misalignment” (3 April 2026). Full list in the Field Guide. The devices on this page are models, not real silicon.

Read the sensor word

-100

Model of an MPU-6050 class accelerometer at its ±2 g range: 16-bit two’s-complement counts, 16,384 counts per g, high byte first in registers 0x3B and 0x3C. The scale is the usual datasheet value for that range (derived here from 32,768 counts across ±2 g); the reading −100 counts is illustrative.

Chapter 0

Why Firmware Starts With Bytes

See how one wrong guess about byte order turns a still board into a falling one, and meet the five ideas that prevent it

You solder an accelerometer to a board and read it. The board lies flat on your desk. The sensor should say about 0 g sideways. Your program says the board is accelerating at −1.55 g, harder than gravity pulls on you. The wire is fine. The sensor is fine. Your program read the right two bytes and then put them together in the wrong order.

That is firmware. Firmware is the program that lives inside a device and talks straight to its hardware: a sensor, a motor, a radio. There is no operating system to hide the details. So you must know what a number looks like in memory, byte by byte, and where the hardware sits in the address space.

Five small ideas

Everything in this lesson comes from five ideas. Each one answers one plain question.

First, bits and masks: how do you change one switch inside a register without touching the seven next to it? Second, fixed-width types: how big is a number, exactly, and what happens at its edge? Third, endianness: which byte of a number comes first in memory? Fourth, alignment: why must a four-byte number sit at an address that divides by four, and what does the chip do when it does not? Fifth, the memory map: why does writing to address 0x40020014 turn on an LED?

We use one real part throughout. The STM32F401RE sits on the Nucleo-F401RE board. It has an Arm Cortex-M4 core, which is a 32-bit processor. A word on this core is 32 bits, or 4 bytes. A halfword is 2 bytes. When another core behaves differently, we say so.

What the hero showed

The hero models a common accelerometer. It keeps its reading in two registers. The first, at 0x3B, holds the high byte: the half of the number that counts big steps. The second, at 0x3C, holds the low byte: the half that counts small steps. The sensor sends the high byte first. If you treat the first byte you receive as the low byte, you swap the halves.

With a true reading of −100 counts, the bytes are 0xFF and 0x9C. In the right order you get 0xFF9C, which is −100 as a 16-bit signed number. Swapped, you get 0x9CFF, which is −25,345. Divide by 16,384 counts per g and the board seems to fall at −1.55 g.

The rule you will use all course. A number in firmware is never just a number. It is a count of bits, a place in memory, and an order of bytes. Check all three before you trust any value.

Try one more thing in the hero. Drag the true reading to +2,400 counts with the wrong order selected. The error is not a small offset. Two bytes in the wrong place turn small values into huge ones. A byte-order bug rarely makes a value slightly wrong. It makes it wildly wrong, and that is how you spot it.

The road

No course slides shape this lesson. We built it from primary sources: the Arm Procedure Call Standard, the vendor’s own header file, Arm’s user guides and a practitioner’s blog. The Field Guide lists each one. If any of this feels fuzzy, the earlier Embedded C lesson and Advanced C cover the C basics we lean on.

  1. Bits and masks: set, clear, toggle and test one bit, and write a whole field.
  2. Fixed-width types: how big a number is, where it wraps, and what C does behind your back.
  3. Endianness: which byte comes first, and how to read a sensor word right.
  4. Struct layout: padding, packing and the bytes you did not ask for.
  5. Misaligned access: what each Cortex-M core does when an address is not a multiple of the size.
  6. The memory map: where flash, RAM and the peripherals live, and what an unmapped address does.
  7. Registers and volatile: why a register write is not a variable write.
  8. Registers as structs: the CMSIS pattern, offsets, and bit-band aliases.
  9. Field Guide: the numbers, a checklist, the core code and where to go next.
A sensor sends the high byte 0xFF first and the low byte 0x9C second. Your code builds the word as (first << 0) | (second << 8). What does it get?

Chapter 1

Bits and Masks

Change one switch in a register without touching its neighbours, using four small operations

Your Nucleo board has a green LED called LD2. It hangs off pin PA5 of the chip. To light it, you must write a 1 into one particular bit of one particular register. The register has 32 bits. The other 31 control other pins. If you write the whole register, you break them.

So you need a way to touch one bit and leave the rest alone. The tool is the mask: a number with a 1 in every bit position you care about and a 0 everywhere else. Think of a stencil. You lay it over the register, and only the cut-out holes can change.

Bits, hex and numbering

A bit is one binary digit, 0 or 1. Programmers number bits from the right, starting at 0. Bit 0 is the least significant bit, the one worth 1. Bit 5 is worth 25, which is 32. So the mask for bit 5 is 32, or 0x20 in hexadecimal. Hex writes four bits as one digit, 0 to 9 then A to F. It is the natural way to read a register: every hex digit is one group of four switches.

In C you build a mask with a shift. The expression 1u << 5 takes the number 1 and moves its bit five places left. The result is 0x20. The u matters: it makes the 1 unsigned, so shifting never reaches the sign bit. We return to that in Chapter 2.

The four operations

Four operations cover almost all register work. Each uses one bitwise operator.

c/* reg is a 32-bit register value; MASK is e.g. (1u << 5) */
reg |= MASK;           /* SET:    bits in the mask become 1 */
reg &= ~MASK;         /* CLEAR:  bits in the mask become 0 */
reg ^= MASK;           /* TOGGLE: bits in the mask flip     */
if (reg & MASK) { }    /* TEST:   non-zero if any masked bit is 1 */

Why do they work? OR with 1 gives 1, and OR with 0 leaves the bit alone. AND with 0 gives 0, and AND with 1 leaves it alone. XOR with 1 flips the bit, and XOR with 0 leaves it alone. In each case the mask decides which bits are touched. The ~ operator flips every bit of the mask, which turns a stencil of holes into a stencil of walls. That is how a clear works: AND keeps the bits where the mask has a 1, so you need the mask to be 0 where you want the clear.

Stencil a register

Tap any bit in the REG, MASK or VALUE rows to flip it. Pick an operation. The RESULT row shows what the line of C would leave in the register. Press Store result to keep it.

A 16-bit slice to keep the cells readable; real STM32F401 registers are 32 bits wide. The preset values (bit 5 of the output data register for PA5, and the two-bit field MODER5 at bits 11:10 with value 01 meaning general-purpose output) come from the STM32F401xE CMSIS header, where GPIO_MODER_MODER5_Pos is 10.

Try the field write. A field is a group of neighbouring bits that mean one thing together. On the STM32F401, each pin has a two-bit mode field in the MODER register. For PA5 the field sits at bits 11:10. The value 01 means “output”. To change a field you must clear the whole field first, then OR in the new value. If you only OR, an old 1 in the field survives and you get the wrong mode.

A worked example

Say MODER reads 0x0000_0C00, which means bits 11:10 hold 11 (analog mode, the reset state of some pins). You want output, 01. Step by step:

  1. Build the field mask: 3u << 10 = 0x0C00. Two bits wide, starting at bit 10.
  2. Clear the field: 0x0C00 & ~0x0C00 = 0x0000.
  3. Build the value: 1u << 10 = 0x0400, which is binary 01 in that field.
  4. OR it in: 0x0000 | 0x0400 = 0x0400. Done.

Skip step 2 and you compute 0x0C00 | 0x0400 = 0x0C00. Nothing changes. The pin stays in analog mode and the LED never lights. The symptom is silent: no error, no fault, just a pin that does nothing. The measurement is to read the register back in a debugger and compare it with what you meant. The fix is to always clear a field before you write it.

Testing a bit and waiting on it

The fourth operation, test, is how firmware asks the hardware a yes or no question. A status register holds flags: one bit says “the byte has been sent”, another says “an error happened”. To ask, you AND the register with the flag’s mask. The answer is zero if the flag is 0 and non-zero if it is 1. You do not compare the result with 1, because the mask may sit at bit 7 and then the answer would be 128.

Here is the worked case. A status register reads 0x0081. Is bit 5 set? The mask is 0x20, and 0x0081 & 0x0020 = 0x0000, so no. Is bit 7 set? 0x0081 & 0x0080 = 0x0080, which is non-zero, so yes. In binary, 0x81 is 1000 0001, so only bits 7 and 0 are set. Count positions from the right, starting at 0. Almost everyone miscounts a bit the first time, which is why the tool above draws every cell.

Name your masks. Write GPIO_MODER_MODER5_Msk and GPIO_MODER_MODER5_0, as the vendor header does, not 0x0C00 and 0x0400. A comment cannot catch a typo in a hex constant. A name can.

On real hardware: on a Nucleo-F401RE, halt the program in a debugger, open the GPIOA registers view, and watch MODER change as you step over each line. Repeat the field write with and without the clear.

A 2-bit field at bits 5:4 holds 10. You want it to hold 01. Which line is right?

Chapter 2

Fixed-Width Types and the Wrap

Pick the exact size of every number, and learn where it wraps and what C quietly does to it on the way

A car odometer shows 999,999 km. Drive one more and it shows 000,000. The odometer did not break. It has six digits and no room for a seventh. Every integer in a chip works the same way, with bits instead of digits.

So the first question for any number in firmware is: how many bits does it have? In desktop C the answer is often “it depends”. On a small chip that is not good enough. A register is exactly 32 bits. A sensor word is exactly 16. A packet field is exactly 8. You need types whose size you can see in their name.

The types that say their size

The header <stdint.h> gives you fixed-width integer types: uint8_t is unsigned with 8 bits, int16_t is signed with 16 bits, and so on up to 64. Use them for anything that touches hardware or a wire. Plain int is whatever the compiler picks. On Arm the Procedure Call Standard (AAPCS32) fixes it: char is 1 byte, short 2, int 4, long 4, long long 8, and a pointer 4. The same standard maps plain char to an unsigned byte. On many desktop compilers char is signed, so code that is right on your laptop can be wrong on the chip.

Unsigned means no negative values: an 8-bit unsigned number runs 0 to 255. Signed numbers use two’s complement: the top bit counts as a large negative weight. An 8-bit signed number runs −128 to +127. Bit pattern 0xFF is 255 unsigned and −1 signed. The bits are the same. Only the reading differs.

Walk round the odometer

The pointer is the value stored in the variable. Choose a type, then press the buttons to add. Cross the red mark and watch the value jump.

The wrap shown is what a plain hardware add does on the low bits. In C, unsigned arithmetic wraps by the language rules. For narrow signed types the add happens in int and the narrowing back is implementation-defined (GCC wraps). Signed overflow of int itself is not defined by C, so never rely on it.

What C does behind your back: promotion

Here is the trap. The C language does arithmetic in int (4 bytes on Arm) or wider. Before any operator runs, every value narrower than int is first widened to int. This is integer promotion. It means the add never overflows 8 bits. Only the store back does.

cuint8_t a = 200, b = 100;
uint8_t s = a + b;        /* a+b is the int 300; stored as 300 mod 256 = 44 */
if (a + b > 255) { }      /* TRUE: compared as int 300, no wrap yet */

uint8_t m = 0x0F;
if (~m == 0xF0) { }      /* FALSE: ~m is the int 0xFFFFFFF0, not 0xF0 */
if ((uint8_t)~m == 0xF0) { } /* TRUE: cast back to 8 bits */

Follow the first line with the numbers. 200 and 100 both become int. The add gives 300. Storing 300 into 8 bits keeps the low 8 bits: 300 − 256 = 44. The second line proves the sum was 300 all along, not 44. The symptom of forgetting this is a comparison that behaves differently from the stored value. The measurement is to print the value before and after the store. The fix is to cast the result back to the type you mean, or to compare before you store.

Shifts and the sign bit

Shifting has its own trap. In 1 << 31 the literal 1 is a signed int. The result needs the sign bit. The C standard does not define the result when a 1 is shifted into the sign bit of a signed type. The fix is the one from Chapter 1: write 1u << 31. Also never shift by the width of the type or more, and never shift by a negative count.

One more rule, because registers are unsigned: use uint32_t for every register value. Mixing a signed and an unsigned operand makes C convert the signed one to unsigned, which turns −1 into 4,294,967,295. A loop like for (uint32_t i = n; i >= 0; i--) never ends, because an unsigned number is always at least 0.

A good habit. Use uint32_t for registers and bit masks, uint8_t for raw bytes, int16_t for signed 16-bit sensor words, and size_t for sizes and indices. Turn on -Wconversion and read what it says.

On real hardware: on a Nucleo-F401RE, write the three lines above into main(), set a breakpoint after each, and read s in the watch window. Then compile with -Wconversion and see which lines the compiler flags.

Signed against unsigned

One more edge needs a number. Suppose int16_t a = -1; and uint16_t b = 1;. Is a < b true? Both are promoted to int first, so the comparison is −1 against 1, and the answer is yes. Now use int32_t a = -1; and uint32_t b = 1;. No type is narrower than int here, so no promotion rescues you. The signed side converts to unsigned: −1 becomes 4,294,967,295, and the answer is no. The same source shape gives opposite answers at two widths.

The symptom is a bounds check or a loop that passes in a test with small types and fails with 32-bit types. The measurement is to print both operands as hex and as decimal. The fix is to keep both sides of a comparison the same signedness, and to let the compiler warn you with -Wsign-compare.

uint8_t x = 250; x += 10; What does x hold, and why?

Chapter 3

Endianness: Which Byte Comes First

Store a 32-bit number in byte-sized boxes, in either order, and learn to read other devices’ numbers safely

Write the number one thousand, two hundred and thirty-four on an envelope. You write the thousands first: 1, 2, 3, 4. A friend from a country that writes the small digits first would write 4, 3, 2, 1. Both can read their own style. They only fight when they swap envelopes.

Memory is a row of byte-sized boxes, each with an address. A 32-bit number needs four boxes. Which box gets the big end of the number? That choice is endianness, or byte order.

Two orders

In little-endian order, the least significant byte goes at the lowest address. In big-endian order, the most significant byte goes at the lowest address. The AAPCS32 standard describes both views of memory in the same way. The Cortex-M4 in the STM32F401 uses the little-endian view, as do Cortex-M parts in general. We call that the native order.

Take the number 0x12345678. Its four bytes are 0x12 (most significant), 0x34, 0x56 and 0x78 (least significant). Store it at address 0x20000000 on a little-endian core. The box at 0x20000000 holds 0x78, the next holds 0x56, then 0x34, and 0x12 sits at 0x20000003. A debugger memory view shows 78 56 34 12. Newcomers often think the debugger is wrong. It is not. It shows bytes in address order.

Fill four boxes

Pick a value and a byte order. The four boxes show what sits at each address. Then choose how the core reads: one byte, a halfword at +0 or +2, or the whole word.

The memory layout rule is the AAPCS32 one: in a little-endian view the least significant byte of an object is at the lowest byte address it occupies. The base address 0x20000000 is the start of SRAM on Cortex-M parts. The values are examples.

Watch what the reads do. On a little-endian core, the byte at +0 is the low byte, 0x78. A halfword read at +0 gives 0x5678, and a halfword read at +2 gives 0x1234. Switch to big-endian and each answer changes. A pointer cast that works on one machine silently gives other numbers on the other.

Where it bites firmware

Your core is not the only chip in the story. Network protocols use big-endian, called network byte order. Many sensors, like our accelerometer, put the high byte at the lower register address. Flash file formats and radios each pick their own order. The data sheet states it. You must read that line.

The safe way to read a multi-byte field from a buffer is to build it from bytes with shifts. The shifts do not depend on your core’s order, because shifts act on values, not on memory.

c/* sensor sends high byte first: buf[0] is the high byte */
int16_t ax = (int16_t)((uint16_t)buf[0] << 8 | buf[1]);

/* WRONG twice: wrong order on a little-endian core,
   and a possibly misaligned 16-bit load (Chapter 5) */
int16_t bad = *(int16_t *)buf;

/* a correct way to swap an already loaded value */
uint16_t sw = __builtin_bswap16(raw);

Work the first line with the hero numbers. buf[0] is 0xFF and buf[1] is 0x9C. Shift 0xFF left 8 to get 0xFF00. OR with 0x9C to get 0xFF9C. The cast to int16_t reads it as signed: 0xFF9C is 65,436 unsigned, and 65,436 − 65,536 is −100. The failing line loads the two bytes as one halfword in little-endian order, which gives 0x9CFF. That is the −1.55 g from the hero. The fix is one line and costs almost nothing.

The symptom of a byte-order bug is a reading that is huge, or that changes sign, when the real value is small. The measurement is to capture the raw bytes (a logic analyser, or a debugger memory view) and compare them with the data sheet’s example. The fix is explicit shifts or a named swap helper.

Reading a 32-bit field the safe way

Now a wider case. A timestamp arrives as four bytes, most significant first: 0x00, 0x01, 0x86, 0xA0. Build it with shifts: (0x00 << 24) | (0x01 << 16) | (0x86 << 8) | 0xA0 = 0x000186A0, which is 100,000. Each byte must be widened first. A uint8_t promotes to a signed int, and shifting 0x86 left by 24 would push a 1 into the sign bit of a signed int, which C does not define. So cast to uint32_t before the shift: (uint32_t)p[1] << 16.

If you already hold the value in a register and only need to flip its order, use a byte-swap helper. __builtin_bswap32(0x12345678) returns 0x78563412 in GCC and Clang. On a Cortex-M4 that compiles to a single REV instruction. You use it when a protocol is big-endian and your data is already in a native uint32_t.

One place for byte order. Put all conversions in small functions such as read_be16(const uint8_t *p) and read_le32(const uint8_t *p). Then the rest of the code never thinks about order, and a test can check each function against the data sheet’s example bytes.

On real hardware: with a Nucleo-F401RE and any I2C accelerometer, read two bytes with a logic analyser attached, and check that the wire order matches the data sheet. Then compare your decoded value with the sensor’s own self-test reading while the board lies flat.

uint32_t v = 0xA1B2C3D4 sits at address 0x20000000 on a little-endian core. What byte is at address 0x20000001?

Chapter 4

Alignment, Padding and Packing

See why a struct is bigger than the sum of its fields, and what you gain and lose by squeezing it

A bookshelf has slots one hand wide. A fat atlas takes four slots. The shop puts the atlas only on a slot number that divides by four, because the shelf bracket is there. If a small book sits before it, a gap stays empty. The shelf is not wasteful. It follows a rule so that every book can be lifted in one grab.

Memory follows a rule like that. The rule is alignment: an object of size N should sit at an address that is a multiple of N. A 4-byte word belongs at 0, 4, 8, 12 and so on. A 2-byte halfword belongs at even addresses. A byte can go anywhere. The AAPCS32 standard states this in its table: byte size 1 and alignment 1, halfword 2 and 2, word 4 and 4, double-word 8 and 8, pointer 4 and 4.

How the compiler lays out a struct

A struct puts several fields in one block, in the order you declare them. The compiler follows two rules. Each field starts at an offset that fits its own alignment, so it inserts padding, unused bytes, before the field when needed. And the whole struct’s alignment is that of its widest field, so its total size is rounded up to a multiple of that.

Take a small record: a flags byte, a 32-bit timestamp, an id byte and a 16-bit voltage. Declared in that order, the offsets are: flags at 0. The timestamp needs a multiple of 4, so bytes 1 to 3 are padding and the timestamp lands at 4 to 7. The id goes at 8. The voltage needs an even address, so byte 9 is padding and the voltage sits at 10 to 11. The total is 12 bytes. The fields add up to only 8. A third of the struct is padding.

Pack the record

Each row is one 4-byte word. Yellow bytes are padding. A red outline marks a field that starts at an address its type does not like. Switch the layout rule and compare the size.

Layout computed with the AAPCS32 rules for byte, halfword and word types. Field names and sizes are an illustrative record, not from a real part. Tail padding rounds the struct up to a multiple of its widest field, which here is 4.

Now look at the other two layouts. Put the widest field first and the fields pack with no padding at all: timestamp at 0 to 3, voltage at 4 to 5, flags at 6, id at 7. That is 8 bytes, with zero waste, and every field is aligned. The cost is that you must remember the order. Packing instead tells the compiler to drop all padding in the declared order. It also gets to 8 bytes here, but the timestamp now starts at address 1. That is a misaligned word. The device marks it red.

The price of packing

Packing looks like free memory. It is not. Memfault’s Interrupt blog (Chris Merck, 3 April 2026) measured the cost on a 19-byte packed sensor record. A 32-bit store to a field at offset 8 compiles to 7 instructions under #pragma pack(1) on a Cortex-M0, against 1 instruction with __attribute__((packed, aligned(4))). The reason: a packed struct has alignment 1, so the compiler must assume every field may be misaligned and splits the store into single-byte stores, even for fields that happen to be aligned. The same post shows the fix keeps the offsets and makes the struct 20 bytes instead of 19.

Compare that with the same record under the natural Cortex-M rules, where a 64-bit timestamp must sit on an 8-byte boundary. The fields are an int64 at 0, two int32 at 8 and 12, a byte at 16 and a uint16 at 18 (byte 17 is padding). That ends at byte 20, and the struct rounds up to 24. So: 19 bytes packed, 20 packed-and-aligned, 24 natural. You choose between size and speed, and you can see both numbers.

ctypedef struct {
    uint8_t  flags;      /* offset 0 */
    uint32_t ts;         /* offset 4: bytes 1..3 are padding */
    uint8_t  id;         /* offset 8 */
    uint16_t mv;         /* offset 10: byte 9 is padding */
} rec_t;                 /* sizeof == 12 */

_Static_assert(sizeof(rec_t) == 12, "rec_t layout changed");
_Static_assert(__builtin_offsetof(rec_t, mv) == 10, "mv moved");

The two _Static_assert lines turn a silent layout change into a compile error. Add one for every struct that is stored, sent or shared with another program.

Do not send a struct over a wire. Padding and byte order differ between compilers and chips. Send bytes you build field by field, as in Chapter 3. Use packed structs only to read a layout you do not control, and pair packed with aligned when you can.

The symptom of a layout surprise is a protocol that works between two builds of your code and fails against another vendor’s. The measurement is to print sizeof and each offsetof. The fix is explicit serialisation plus static asserts.

On real hardware: build the record for a Nucleo-F401RE, open the .map or use arm-none-eabi-gdb with ptype /o rec_t to print offsets, and compare them with the device above.

struct { uint8_t a; uint32_t b; uint8_t c; } with natural alignment on a Cortex-M. What is its size?

Chapter 5

The Misaligned Load

Ask a core to load a word from an address that does not divide by four, and see which cores cope and which fault

A pointer to a packed struct, a cast over a receive buffer, a field read at offset 1: each hands the core an address that is not a multiple of the load size. The program compiles. It may even pass on your desk. Then a different chip, or a different compiler flag, turns the same line into a crash with no message.

A misaligned access (also called an unaligned access) is a load or store whose address is not a multiple of its size. Reading 4 bytes from address 0x20000001 is one. What happens next depends on the core, the instruction and one control bit.

What the memory system wants

Memory is built around aligned words. A word load at an aligned address is one transfer on the bus. A word that starts at 0x20000001 covers bytes 1 to 4. Those bytes live in two different aligned words, so a simple memory system cannot fetch them in one go.

Cores answer in three ways. The small Cortex-M0 and M0+ (the Armv6-M cores) do not support unaligned accesses: the access raises a HardFault, the exception for errors the core cannot recover from. The Cortex-M3 and M4 (Armv7-M) do the work for you. They split the access into several aligned transfers. It is slower but it succeeds. And the M3 and M4 have a control bit that turns this help off.

Arm’s Cortex-M4 user guide lists exactly which instructions get that help: the single-register loads and stores LDR, LDRH, LDRSH, STR and STRH (and their unprivileged forms). The multi-register and double-word instructions LDM, STM, LDRD and STRD always fault on an unaligned address, whether or not the control bit is set. That control bit is UNALIGN_TRP, bit 3 of the Configuration and Control Register (CCR) at 0xE000ED14. When it is 1, even an unaligned LDR faults. Floating-point loads such as VLDR also fault.

Load from an odd address

Choose a core and an instruction, then drag the address. Aligned loads always work. Slide to an odd address and see what each configuration does.

0x20000001

A rule model of the documented behaviour: which instructions tolerate misalignment, what UNALIGN_TRP changes, and which fault results. It does not model cycle counts, which differ by core and memory. The UsageFault escalates to HardFault with HFSR.FORCED set because UsageFault is disabled at reset. Check the Technical Reference Manual of your own core.

Try the default first: Cortex-M4, LDR, offset 1. The load works and the card says it touched two aligned words. Then flip to UNALIGN_TRP and the same line faults. Switch to M0+ and it faults without any bit being set. Finally pick LDM at offset 1 on the M4: it faults on every setting.

Reading the fault

When an unaligned access traps, the core raises a UsageFault. Its status bit UNALIGNED is bit 24 of the Configurable Fault Status Register (CFSR at 0xE000ED28). At reset the UsageFault handler is not enabled, so the fault escalates to a HardFault, and bit 30 (FORCED) of the HardFault Status Register (HFSR at 0xE000ED2C) says so. A fault handler that reads CFSR and the stacked program counter finds the exact instruction. On M0+ there is no CFSR: you get a plain HardFault and must read the stacked PC yourself.

c/* CCR at 0xE000ED14: bit 3 UNALIGN_TRP */
#define SCB_CCR  (*(volatile uint32_t *)0xE000ED14u)
SCB_CCR |= (1u << 3);              /* trap unaligned LDR/STR in development */

uint8_t buf[8] = {0,1,2,3,4,5,6,7};
uint32_t x = *(uint32_t *)&buf[1]; /* UsageFault now; also not valid C */

uint32_t y; memcpy(&y, &buf[1], 4); /* correct: the compiler picks safe loads */

Follow the example. The array may start at an aligned address, but &buf[1] is one byte after it. Casting that to a uint32_t * and dereferencing tells the compiler the address is aligned, which it is not. With the trap bit on, you fault at that line. With it off on an M4 you silently pay extra bus transfers, and on an M0+ you fault. The memcpy version is the portable fix. The compiler knows the real alignment is 1 and emits byte loads or an unaligned-safe load.

Turn the trap on while developing. Setting UNALIGN_TRP on an M3 or M4 makes every hidden misaligned access visible on your desk, on the chip that tolerates it, before the code reaches an M0+ that would not. If a fault is a mystery, read CCR once at boot and check bit 3.

Symptom, measurement, fix. The symptom is a HardFault on one chip and not on another, often at a line that reads a field from a buffer. The measurement is the stacked PC plus CFSR bit 24. The fix is to stop casting buffer addresses to wider pointers: use memcpy, byte shifts (Chapter 3), or align the buffer with __attribute__((aligned(4))).

On real hardware: on a Nucleo-F401RE set bit 3 of SCB->CCR, then run the cast above and read SCB->CFSR in the HardFault handler. Bit 24 should be set. Clear the bit and measure the same load with the DWT cycle counter to see the extra cost.

On a Cortex-M4 with UNALIGN_TRP = 0, which of these faults?

Chapter 6

The Memory Map

Learn which addresses reach flash, which reach RAM, which reach hardware, and what happens at an address nobody answers

A city has street numbers. Number 10 is a bakery, number 20 is a school, and number 9,999 is an empty field. You can post a letter to any of them. What happens depends on who lives there.

A 32-bit core has the same idea. It can put any of 232 numbers, 4,294,967,296 of them, on its address lines. That is 4 GiB of possible addresses. Only a few are backed by something real. The chip’s designer decides which address reaches which block of silicon. That plan is the memory map.

One map for everything

The big idea is that the core uses one kind of instruction to reach all of it. A load from flash, a store to RAM and a write to an LED pin all use the same LDR and STR. Only the address differs. When an address reaches a peripheral instead of memory, we call it memory-mapped I/O. A peripheral is a hardware block on the chip: a GPIO port, a timer, a serial port. Its control and data registers sit at fixed addresses.

Arm splits the 4 GiB into regions. For Armv7-M cores such as the Cortex-M4, the plan is: Code at 0x0000_0000 to 0x1FFF_FFFF, SRAM at 0x2000_0000 to 0x3FFF_FFFF, peripherals at 0x4000_0000 to 0x5FFF_FFFF, external RAM at 0x6000_0000 to 0x9FFF_FFFF, external devices at 0xA000_0000 to 0xDFFF_FFFF, and the Private Peripheral Bus at 0xE000_0000 up. The Private Peripheral Bus holds the core’s own parts: the system control block, the SysTick timer, the interrupt controller, and the debug unit. The CCR from Chapter 5 lives there.

The chip vendor then fills in the regions. On our STM32F401RE the CMSIS device header gives the facts: flash starts at 0x0800_0000 and ends at 0x0807_FFFF, which is 512 KB. SRAM1 starts at 0x2000_0000 and is 96 KB, so it ends at 0x2001_7FFF. The peripherals start at 0x4000_0000, with three bus windows: APB1 at 0x4000_0000, APB2 at 0x4001_0000 and AHB1 at 0x4002_0000. Another window, AHB2, starts at 0x5000_0000.

Who answers at this address?

Type a hex address or pick one. The bar is the full 4 GiB map. The marker shows where the address lands, and the card names the block that answers.

Region boundaries are the Armv7-M ones. Flash, SRAM1 and bus-window start addresses and sizes come from the STM32F401xE CMSIS header (FLASH_BASE 0x08000000, FLASH_END 0x0807FFFF, SRAM1_BASE 0x20000000, 96 KB, PERIPH_BASE 0x40000000, AHB1 at +0x20000, AHB2 at +0x10000000). Register names and offsets for GPIOA and RCC are from the same header. Window ends are rounded and the error response is a model.

Click the chips in order. The first lands in flash: that is where your program lives, and where the core fetches instructions. The second is RAM: your variables, the stack and the heap. The third, 0x4002_0014, is the GPIOA output data register, which drives pin states. The fourth is the RCC clock register that must be switched on before GPIOA works at all (Chapter 7). The fifth is a register inside the core itself.

The address nobody answers

Now type 0x2001_8000, the first address past the end of SRAM1. The map has no RAM there. On a real part the bus gives an error response, and the core raises a BusFault: a fault for a bad bus access. If the BusFault handler is not enabled, it escalates to a HardFault, as in Chapter 5. When the fault is precise, the Bus Fault Address Register (BFAR) holds the bad address, and the CFSR tells you which bit to check.

This failure is easy to cause. Index past the end of an array that sits last in RAM, or dereference a pointer that holds an old value. The symptom is a HardFault at one line. The measurement is the stacked program counter and the address in BFAR. The fix is to compare that address with the map above. If it falls in a gap, you have a stray pointer. If it falls in flash, you tried a plain store to flash, which does not program it.

Keep the map in your head. 0x0800_0000 is code, 0x2000_0000 is data, 0x4000_0000 is hardware, 0xE000_0000 is the core. A pointer whose top hex digit is none of these is almost certainly a bug.

A last point on the Code region. After reset, the core reads its first two words from address 0x0000_0000: the starting stack pointer and the address of the reset handler. On STM32 parts the boot pins choose what is aliased there, normally the flash from 0x0800_0000. The next lesson, Reset to main(), follows that jump. For the core’s view of the same ideas, see the pipeline and privilege lesson.

On real hardware: on a Nucleo-F401RE, open the debugger memory view at 0x08000000, 0x20000000 and 0x40020000. Flash shows your code. RAM shows your data. The GPIOA block shows register values, MODER first. Then read 0x20018000 and see what your debugger reports.

On the STM32F401RE, a store goes to address 0x4002_0014. Where does it land?

Chapter 7

Registers Are Not Variables

Write to hardware with volatile, and see how a three-step update can lose a change when an interrupt lands in the middle

You flip a light switch. The light is on. You walk away and someone else flips another switch on the same wall plate. If both of you copy the wall plate’s state to paper, change one line and write the whole plate back, the second person’s change can vanish. That is a read-modify-write race.

A memory-mapped register looks like a variable in C, but it is a window onto hardware. Reading it may return a value the hardware changed a moment ago. Writing it may start something: turn on a pin, send a byte, clear a flag. Two facts follow. The compiler must not be clever about registers. And updating one bit of a register has hidden steps.

volatile: do exactly what I wrote

A compiler optimises. If you read a variable twice and nothing in your code changes it, the compiler may read it once. For a register that is wrong, because hardware changes it. The keyword volatile tells the compiler: every read and write in the source must happen, in the order written. The vendor header marks every register field __IO, which is volatile.

c/* STM32F401 USART2 status register; TXE flag = bit 7 */
#define USART2_SR  (*(uint32_t *)0x40004400u)           /* no volatile */
while (!(USART2_SR & (1u << 7))) { }               /* may compile to an endless loop */

#define USART2_SR_V  (*(volatile uint32_t *)0x40004400u)
while (!(USART2_SR_V & (1u << 7))) { }             /* reloads the register each pass */

Without volatile, the compiler sees a loop that never changes the register, loads it once, and spins on the stale copy. The program hangs with optimisation on and works with it off. That mismatch is the classic symptom. The measurement is to compare the disassembly at -O0 and -O2. The fix is the one keyword. (The USART2 base 0x4000_4400 is APB1 plus 0x4400 in the CMSIS header; the TXE position is from the F4 family reference manual, so check it for your part.)

A blink from real addresses

Now put Chapters 1 and 6 to work. To blink LD2 on PA5 of the Nucleo-F401RE you do three things. The peripheral clock must be on first, or writes to GPIOA are ignored. Then set the pin mode. Then write the pin.

cRCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;                    /* RCC at 0x40023800, offset 0x30, bit 0 */
GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER5_Msk)   /* clear the 2-bit field at bits 11:10 */
               | GPIO_MODER_MODER5_0;                      /* 01 = output */
GPIOA->ODR ^= GPIO_ODR_OD5;                                /* toggle PA5: at 0x40020014, bit 5 */

The race in the middle

The last line hides three steps. The core loads ODR into a core register, flips bit 5 in the core register, and stores the result back to ODR. Between the load and the store, an interrupt can fire. An interrupt is a signal that makes the core pause your code, run a short handler called an interrupt service routine (ISR), and then resume. If the ISR changes another bit of ODR in that gap, your store writes the old copy back and wipes out the ISR’s change.

Land the interrupt

Main code sets PA5. An interrupt sets PA6. Choose how main writes the pin, then slide where the interrupt lands, and press Run. Check whether both pins end up lit.

A model of the timing, not of silicon. On a Cortex-M the core finishes the current instruction (or abandons and restarts a multi-cycle one) before taking an interrupt, so it can land between the load and the store as shown. BSRR is the GPIO bit set/reset register at offset 0x18: writing a 1 to bit n sets pin n, writing a 1 to bit n+16 clears it, and a 0 changes nothing.

With ODR |= bit and the interrupt landing after step 1 or 2, PA6 is lost. Landing before step 1 or after step 3 is safe. So the bug shows up only on the rare runs where the timing aligns. That is the worst kind of bug: it is rare and it vanishes under a debugger.

The register BSRR is the cure for this exact problem. It is a write-only set/reset register. Bits 0 to 15 set pins, bits 16 to 31 clear pins, and writing a 0 does nothing. One store changes one pin and leaves the others alone, with no read first. The vendor header defines GPIO_BSRR_BS5 (bit 5) and GPIO_BSRR_BR5 (bit 21). Many peripherals have this style: set registers, clear registers, or flags you clear by writing a 1.

The clock gate you cannot see

One more register fact catches every beginner. On the STM32F4, a peripheral has its clock off at reset to save power. While the clock is off, a write to its registers has no effect and a read does not return what you wrote. The code compiles, the debugger shows the register stuck at its reset value, and there is no fault. The switch is bit 0 of RCC_AHB1ENR, at 0x40023830, for GPIOA. The symptom is a register you write and then read back unchanged. The measurement is to read the enable bit. The fix is to set it first and, if you want to be careful, read the register once afterwards so the write has landed before the next access.

Prefer registers built for atomic bits. If a peripheral gives you a set/clear register, use it for single bits. If it does not, wrap a shared read-modify-write in a short interrupt-disabled section, or make sure only one context ever touches that register.

On real hardware: on a Nucleo-F401RE, toggle PA5 in main with ODR ^= while a timer ISR toggles PA6 at a high rate with the same method. Count the missed toggles with a logic analyser, then switch both to BSRR and repeat.

Why can two writers, main code and an ISR, both safely set different pins of GPIOA when they use BSRR but not when they use ODR |= bit?

Chapter 8

A Struct Laid Over Hardware

Name every register with one struct and one base address, and see how a single wrong member type moves every register after it

A hotel has a front desk with a key rack. Every key hook has a number. Hook 20 is room 20. If the person who built the rack skipped one hook, every key after it hangs one place too far along. You open the wrong door and never see why.

A peripheral is like that rack. GPIOA has ten registers in a row: MODER at offset 0x00, OTYPER at 0x04, OSPEEDR at 0x08, PUPDR at 0x0C, IDR at 0x10, ODR at 0x14, BSRR at 0x18, LCKR at 0x1C, and the two alternate-function registers AFR[0] and AFR[1] at 0x20 and 0x24. Those offsets are in the STM32F401 CMSIS header. A raw #define for each one works, but a struct is neater.

The overlay pattern

You declare a struct whose members match the register list, in order, each 32 bits wide. Then you cast the peripheral’s base address to a pointer to that struct. The compiler turns GPIOA->ODR into a load or store at base plus the member’s offset. This is the pattern the vendor header uses. It is also the first layer of a driver: the register map becomes a type.

ctypedef struct {
  volatile uint32_t MODER;    /* 0x00 */
  volatile uint32_t OTYPER;   /* 0x04 */
  volatile uint32_t OSPEEDR;  /* 0x08 */
  volatile uint32_t PUPDR;    /* 0x0C */
  volatile uint32_t IDR;      /* 0x10 */
  volatile uint32_t ODR;      /* 0x14 */
  volatile uint32_t BSRR;     /* 0x18 */
  volatile uint32_t LCKR;     /* 0x1C */
  volatile uint32_t AFR[2];  /* 0x20, 0x24 */
} GPIO_TypeDef;

#define GPIOA  ((GPIO_TypeDef *)0x40020000u)   /* AHB1 base + 0x0000 */
_Static_assert(__builtin_offsetof(GPIO_TypeDef, ODR) == 0x14, "ODR offset");

The volatile on each member is Chapter 7. The static assert is Chapter 4: it fails the build if anyone changes a member and shifts the layout. Because every member is 32 bits wide and 4-byte aligned, the compiler adds no padding. That is exactly why you use uint32_t and not int or uint16_t for registers.

Hang the keys

Choose a version of the struct. Each row shows where the compiler thinks a member lives against where the hardware really puts it. Then pick a line of code and read where its store goes.

Offsets are from the STM32F401xE CMSIS header (GPIO_TypeDef), with GPIOA at 0x40020000. The wrong versions are deliberate mistakes. The effect on the real register (writing a whole value to ODR, or writing to read-only IDR) follows the register roles in the reference manual: IDR is read-only, ODR holds all 16 outputs, BSRR is write-only.

With the correct version, GPIOA->BSRR = 0x20 is a store to 0x40020018: set PA5. Switch to “Skipped OTYPER”. Every member after MODER sits 4 bytes too early. The line still compiles and still looks right. But BSRR now sits at 0x40020014, which is the real ODR. Writing 0x20 there sets PA5 and clears the other fifteen outputs. Nothing warns you. The symptom is some other LED that goes off when you set this one. The measurement is a print of each member’s address, or a static assert on offsetof. The fix is to copy the layout from the reference manual or the vendor header, member for member.

The “narrow types” version shows a second trap. Declare IDR and ODR as 16-bit and ODR moves to 0x12, while BSRR moves to 0x14. The register map says registers are 32-bit words, so use 32-bit types.

Bit-band: one bit through an address

Chapter 7 ended with a race on a three-step update. The Cortex-M3 and M4 offer another answer: bit-banding. The core maps each bit of a bit-band region onto its own 32-bit word in a larger alias region. A write to that word sets or clears just that one bit, as an atomic read-modify-write done by the hardware. The STM32F4 CMSIS header names the bases: peripheral bit-band alias PERIPH_BB_BASE = 0x42000000 for the peripheral region at 0x40000000, and SRAM1_BB_BASE = 0x22000000 for SRAM at 0x20000000.

The alias address is: alias base + (byte offset from region base × 32) + (bit number × 4). Work it for PA5 in ODR. The byte offset is 0x40020014 − 0x40000000 = 0x20014. Times 32 is 0x400280. Add bit 5 times 4, which is 20 or 0x14: 0x400294. Add the alias base: 0x42400294. Writing 1 to that address sets PA5 and nothing else.

c/* alias = BB_BASE + (byte_offset * 32) + (bit * 4) */
#define BB_PERIPH(addr, bit) (*(volatile uint32_t *)(0x42000000u + \
        (((uint32_t)(addr) - 0x40000000u) << 5) + ((bit) << 2)))

BB_PERIPH(&GPIOA->ODR, 5) = 1;   /* stores to 0x42400294; sets only PA5 */

Do not count on bit-banding everywhere. It exists on Cortex-M3 and M4 parts such as this one, but the Cortex-M0+ does not have it, and neither do other newer cores. Read your core’s manual. On the STM32F401 the clean portable answer is still BSRR, which every Cortex-M with this GPIO block supports.

Why the struct must match the manual exactly

It helps to see the cost in numbers. There are ten GPIO registers, each 4 bytes, so the block spans 0x28 bytes, 40 in decimal. The next GPIO port, GPIOB, starts at 0x40020400, which is 0x400 or 1,024 bytes after GPIOA. A port therefore has 984 bytes of address space beyond its ten registers that map to nothing in this struct. If your struct is wrong by one member, you will not step over into GPIOB. You will quietly write to the wrong register of the same port, and the port is still “working”. That is why the failure is so hard to find: the symptom moves around with each wrong write.

Two habits make this safe. Generate or copy the struct from the vendor header and never retype it. And add one static assert on the last member’s offset: if AFR[1] is not at 0x24, something above it is wrong.

Registers as bit fields in C? You can declare a struct with unsigned x : 2; members to overlay register fields. The C standard leaves the order of bit-fields inside a unit to the implementation, and volatile accesses to them have extra rules, so many teams avoid this for hardware. Masks and shifts, with names, are the portable choice.

On real hardware: on a Nucleo-F401RE, print (uint32_t)&GPIOA->BSRR over a serial port or read it in the debugger. It must equal 0x40020018. Write 1 to 0x42400294 and watch LD2 light.

A GPIO_TypeDef declares MODER, OSPEEDR, PUPDR, IDR, ODR, BSRR as uint32_t, with OTYPER forgotten. Where does GPIOA->BSRR = 0x20 write?

Chapter 9

Field Guide

Review the numbers, run the checklist, keep the core code and find the next lesson

You can now read memory the way firmware does. A number has a width, a byte order and an address. A struct has padding you can see. A load has an alignment rule that depends on the core. A register is a window onto hardware, so it needs volatile, and a three-step update on it can race with an interrupt.

The numbers that matter

WhatNumberWhy it matters
Arm 32-bit type sizes (AAPCS32)char 1, short 2, int 4, long 4, long long 8, pointer 4; alignment equals size, 8 for double-wordUse fixed-width types anyway; plain char is unsigned here
The four bit operations|= set, &= ~ clear, ^= toggle, & testA field needs clear then set
Wrap of 8-bit and 16-bituint8_t 255 to 0; int8_t 127 to −128; 200 + 100 stores 44Promotion computes in int, the store narrows
0x12345678 little-endian78 56 34 12 from the lowest addressThe core is little-endian; many sensors are not
Accelerometer, ±2 g16,384 counts per g; 0xFF9C = −100; swapped 0x9CFF = −25,345A byte swap makes small values huge
Sensor record (Interrupt post)19 bytes packed, 20 packed and aligned(4), 24 natural; store costs 7 vs 1 instructions on a Cortex-M0Packing trades speed and safety for size
Misaligned load, Cortex-M0+HardFaultArmv6-M has no unaligned support
Misaligned load, Cortex-M4LDR, LDRH, STR, STRH work; LDM, STM, LDRD, STRD faultUNALIGN_TRP is CCR bit 3 at 0xE000ED14
Fault registersCFSR 0xE000ED28, UNALIGNED bit 24; HFSR 0xE000ED2C, FORCED bit 30They name the cause of the fault
STM32F401RE memoryFlash 0x08000000, 512 KB; SRAM1 0x20000000, 96 KB; peripherals 0x40000000Know the map before you debug a pointer
GPIOA on the Nucleobase 0x40020000; ODR +0x14; BSRR +0x18; MODER5 bits 11:10; RCC AHB1ENR 0x40023830 bit 0Clock first, mode next, then write
Bit-band alias0x42000000 + byte offset × 32 + bit × 4; GPIOA ODR bit 5 is 0x42400294Cortex-M3 and M4 only

The pre-flight checklist

  1. Width: Is every register, mask and wire field a fixed-width unsigned type?
  2. Masks: Is every mask built with 1u and named?
  3. Fields: Do multi-bit writes clear the field before they set it?
  4. Order: Did you read the data sheet for the byte order of each external field?
  5. Layout: Does a static assert pin sizeof and offsetof of every shared struct?
  6. Casts: Is any buffer address cast to a wider pointer? Use memcpy or shifts.
  7. Registers: Is every register access volatile, and is a shared one set through a set/clear register?
  8. Trap: Is UNALIGN_TRP on in debug builds on cores that have it?

The core as code

c#include <stdint.h>
#include <string.h>

/* 1. bits and fields */
#define BIT(n)            (1u << (n))
#define SET_BITS(r, m)    ((r) |= (m))
#define CLR_BITS(r, m)    ((r) &= ~(m))
#define SET_FIELD(r, m, v) ((r) = ((r) & ~(m)) | ((v) & (m)))

/* 2. byte order, independent of the core */
static inline int16_t  read_be16(const uint8_t *p) { return (int16_t)(((uint16_t)p[0] << 8) | p[1]); }
static inline uint32_t read_le32(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; }  /* valid on little-endian cores */

/* 3. a pinned layout */
typedef struct { uint32_t ts; uint16_t mv; uint8_t flags, id; } rec_t;
_Static_assert(sizeof(rec_t) == 8, "rec_t size");

/* 4. the register overlay and a blink on PA5 (Nucleo-F401RE) */
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
SET_FIELD(GPIOA->MODER, GPIO_MODER_MODER5_Msk, GPIO_MODER_MODER5_0);
GPIOA->BSRR = GPIO_BSRR_BS5;                 /* on  */
GPIOA->BSRR = GPIO_BSRR_BR5;                 /* off */

Where it sits in the field

This is step 1 of the Firmware from Zero series. It sits after the survey lessons Embedded Systems Intro and Embedded C, and the deeper Advanced C. Everything later assumes it. A driver for a sensor over I2C needs byte order and a register map. A DMA transfer needs aligned buffers. A bootloader needs the memory map and the layout of a header struct.

Keep going

The takeaway. Firmware reads memory as bits, in a fixed width, in a known byte order, at an address that fits its size, inside a map the chip designer drew. Check those four things and most first-week bugs disappear.

Sources and credit

No course slides were used. The facts come from sources opened for this lesson. Where a source was only seen through a quotation, the list says so.

A packed struct is read through a pointer on a Cortex-M0+, and the board HardFaults on one field only. What is the most likely cause?

Now press Teach and explain one sensor word out loud, from memory: its width, its byte order, the address where it lands, why the load is aligned, and how you would write one bit of the register that controls the sensor. Then go back to the sensor at the top, flip the byte order, and explain the −1.55 g.

Firmware from Zero, step 1: Bits, Fixed-Width Types, Endianness, Alignment and Memory-Mapped Registers
Back to Embedded C · Next: Reset to main()