# From ARM's Cortex-M0+ reference delivery to an MCU that runs C firmware

The Cortex-M0+ delivery from ARM includes a core you can synthesise, but not an MCU you can use. This article is a record of turning one into a system that boots and runs C firmware. Three things get most of the space: the transfer boundary an arbiter is most likely to get wrong when a single-master bus grows a second master, why a module-level testbench can be all green and still fail on the full chip, and what order to look at things in when it hangs.

## Where the delivery actually starts: three layers

Three layers matter. `CM0PIKMCU` at the top is an example system; `CM0PMTBINTEGRATION` wraps the core and the DAP behind a black box with parameters (`NUMIRQ`, `VTOR`, `WIC`, `MPU` are all decided there); and `cm0p_ik_sys` in the middle is the system layer ARM explicitly says you are meant to replace. Address decoding lives in `cm0p_ik_ahb_interconnect`: eight slave ports, m0 is the default slave, m1 through m7 are usable, each with `base`, `width` and `enable`, compared as `HADDR[31:width]` against the same bits of the base — so the regions must not overlap. Turn MTB off and m7 frees up, but one AHB slave port still takes exactly one peripheral. To add a dozen peripherals the only sane option is an AHB-to-APB bridge plus an APB peripheral bus, with the bridge occupying a single slave port.

That choice paid off: every peripheral after that was its own module with its own testbench, and adding one touches a slot table and a handful of wires.

## What it grew into

`mcu_top` handles PMU, reset and clocking (no PLL — everything runs on HCLK), and `mcu_sys` holds the core, the two-master arbiter, AHB decoding, flash and SRAM, the APB bridge and the APB slot decoder. Addresses, interrupt numbers and clock-gate bits are defined once in `mcu_map.vh`, with the C header mirroring the same table. That single source saved more time than expected: adding a peripheral means editing two files in step instead of hunting constants in several places.

Thirteen peripherals now: three GPIO ports, two UARTs, three timers, SPI, I2C, a watchdog, a real-time counter, system control, a flash controller, and a two-channel DMA. Memories start as behavioural models with the interface of an ASIC macro — synchronous single port, one-cycle read latency, four byte enables — so swapping in a memory-compiler macro later does not disturb anything above them.

## The first four things that bite when you add a peripheral

Write data arrives one cycle late. `HWDATA` is only valid in the data phase, while the address is already gone. So the write enable and the byte mask have to be registered for one cycle and the data latched on the following one. Sampling in the address phase stores the previous transfer's data instead, which shows up as "I wrote a value and read back the last one".

A zero-wait slave needs a latched address for its read mux. By the data phase `HADDR` already points at the next transfer, so a read mux built on the live address returns a different register.

Byte strobes have to be derived from `HSIZE` and `HADDR[1:0]` into a four-bit lane mask. Skip it and a `*(uint8_t*)` access corrupts the neighbouring byte.

Don't aim a timer's equality compare too close. My first version used `cmp = count + 4`, which the gap between two register accesses walked straight past, so the interrupt never came. A larger offset, or a `>=` compare, fixes it.

## Two masters: the one cycle an arbiter gets wrong

This is the one problem in the project that took real time to find, so it gets its own section.

A core plus a DMA is a two-master AHB-Lite system. The arbiter has to answer one question: who owns the bus. The intuitive answer is to look at `HTRANS` — anything but IDLE means the master wants it. But a master drops `HTRANS` back to IDLE after its address phase and waits for data. Treat IDLE as "it does not want the bus" and the arbiter hands the bus to the other master while the first is still waiting; its `HREADY` stays low and that read never completes. In simulation the core's program counter turns into X and the firmware hangs, which looks a lot like "something corrupted the core". So each master needs a `pend` flag: set when its address phase is accepted, held while it is not granted, cleared when the data phase completes. "Wants the bus" then means `HTRANS` is not IDLE or `pend` is set.

That alone is not enough. `pend` describes the previous cycle, and on the very cycle an address phase is accepted, `pend` is only set at the end of it. The switch decision runs on the same clock edge and still reads the old zero, so ownership moves on that cycle — the slave has already taken the access and completes it while the DMA holds the bus, and by the time the bus comes back the response data belongs to someone else. The core reads garbage or X, a register is poisoned, and eventually a HardFault follows. The fault location drifts with the code layout: add one print and it breaks somewhere else.

The decision has to include the address phase being accepted in the current cycle:

```verilog
wire m0_accept   = M0_HREADY & M0_HTRANS[1];
wire m0_inflight = m0_accept | pend0;           // in flight = accepted now + left over
wire hold_core   = M1_LOCK & ~owner & ~pend0;   // DMA wants it, core is free
assign M0_HREADY = (owner | hold_core) ? 1'b0 : HREADY;
```

Handover only happens at a transfer boundary where `inflight` is zero, and the master about to lose the bus is held first — its next address phase gets `HREADY` low so it stops cleanly on the boundary, and ownership changes on the following cycle. That way a slave never accepts an unclaimed access in the middle of a handover.

There is a trap on the other side too. If the rule is tightened to "no transfer may be in flight anywhere", a core polling in a tight loop during a DMA transfer leaves `HTRANS` busy almost every cycle, the arbiter never sees a window, and the DMA only runs after the driver's poll loop times out — which looks like a driver timeout even though the data is correct.

## Why verification lies

The module-level two-master testbench was green from the start and broke the moment the real core was connected. The cause was my own AHB master BFM: it sampled `HREADY` after the clock edge, so it read the next cycle's value and treated "held back, address not accepted" as "accepted", then waited for a data phase that never existed. A real core is pipelined with completely different `HTRANS` timing, and it walked straight into both rules above.

The fix is to register `HREADY`, `HTRANS` and `HRDATA` on the edge and judge from the previous cycle's values instead of reading combinational signals after it. Only then did the module-level test reproduce the failure shape seen on the full chip.

The lesson matters more than the bug: multi-master logic cannot be trusted to a single-master BFM; it has to run a concurrency case against the real core in the full-chip testbench. And the way to tell whether a simulation is actually stable is whether it finishes at exactly the same time every run. Jitter means something still depends on timing — a far more sensitive signal than passing three runs in a row.

## What to look at, in order, when it hangs

First, find where the core is parked. A small constant that jumps to itself is `Default_Handler`, i.e. a HardFault, not a bus deadlock; `objdump` on that address tells you which.

Then add a HardFault handler to the firmware that drops the exception frame (r0–r3, r12, lr, pc, xpsr, plus r4–r7 while you are there) into an SRAM mailbox for the testbench to print. This pays for itself: the console pushes characters out through GPIO pins and drops them when the firmware writes back to back, so a `puthex` dump of the registers often comes out as half a line, while the mailbox is reliable.

Next, hang a probe on `HRESP`. A HardFault with no error response is almost always an unaligned access, an illegal instruction, or X that has already reached a register — in which case look at which registers in the exception frame are unknown.

And hold each phase of a console character for three cycles at some point; missing characters will steer your diagnosis the wrong way.

## Choices in the individual blocks

The flash read path is its own AHB slave with configurable wait states, with the array's chip select driven in the address phase so its registered output lands exactly in the data phase. The array address is a word address, `HADDR[19:2]`; truncating to the low bits silently aliases distant addresses into the low 256 KB, which shows up as "I programmed it and cannot read it back". Semantically it is NOR: programming can only turn 1s into 0s (`mem &= data`), a sector erase returns all ones, so programming twice yields the AND of the two values rather than the second overwriting the first — a good self-test in itself. A protection boundary keeps the boot area readable but not writable.

The real-time counter currently divides PCLK down to a one-second tick, which is enough to verify behaviour, but a real chip needs a separate 32.768 kHz domain whose cross-domain register accesses use two-flop synchronisers and a handshake. I wrote that down explicitly as a reserved change point rather than leaving it vague — otherwise it reads as an omission at review time.

The DMA enable has to start on a rising edge. With a level, the enable has not been cleared on the cycle the engine finishes and it immediately runs the whole transfer again, which looks like "it copied eight words and would not stop". The engine also leaves two idle cycles between words so the arbiter has a chance to hand over.

## Where it stands

Twelve simulations pass: eleven module testbenches plus the full-chip C firmware self-test, and the full chip finishes at exactly the same time across repeated runs. The firmware exercises peripheral IDs, UART loopback on two paths, timer interrupts, real SPI and I2C traffic, RTC counting and alarm, flash program and erase, and DMA copies, then goes through a genuine soft reset and checks the reset cause and that SRAM survived it. Lint is clean.

What is not done is stated just as plainly: an independent clock domain for the RTC, execute-while-programming for the flash (the model allows it, real NOR does not), DMA scatter-gather and half-transfer, DFT, and physical implementation. Those belong to the next step, not to a claim that everything is finished.

