Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Microcontroller Architecture

The CPU Core and the Instruction Cycle

See how a microcontroller CPU works: registers, program counter, stack pointer, status flags, the fetch-decode-execute cycle and pipelines, with a tiny CPU simulator in C.

Your C code never mentions registers or instruction fetches, but every line of it becomes machine instructions that a small piece of hardware executes one after another. Knowing how that hardware works helps you read disassembly, understand why interrupts behave the way they do, and predict what a + b costs. You do not need to become an assembly programmer, but you should know the cast of characters.

In this lesson you meet the registers of a typical 32-bit core, follow the fetch-decode-execute cycle, learn about pipelines and condition flags, and then build and run a tiny CPU in about sixty lines of C.

The registers

Registers are the CPU's own tiny, very fast storage cells. Arithmetic happens between registers; loading and storing moves values between registers and memory. An ARM Cortex-M has sixteen 32-bit registers visible to the programmer:

Register Name Role
R0-R3 arguments pass the first four function arguments; R0 holds the return value
R4-R11 general local variables; a called function must preserve them
R12 IP scratch register
R13 SP stack pointer: top of the stack
R14 LR link register: return address of the current function call
R15 PC program counter: address of the next instruction
xPSR status condition flags (N, Z, C, V) and the current exception number

The three special registers are worth memorizing:

  • The program counter (PC) holds the address of the instruction being fetched. It advances automatically; a jump or a function call writes a new value into it.
  • The stack pointer (SP) points at the top of the stack in RAM, where function calls store return addresses, saved registers and local variables.
  • The link register (LR) remembers where to come back to after a call. A function return is "copy LR into PC".

Status flags

After many arithmetic instructions the CPU records facts about the result in flag bits:

  • Z (zero): the result was 0.
  • N (negative): the top bit of the result is 1.
  • C (carry): an unsigned overflow occurred (a carry out of the top bit).
  • V (overflow): a signed overflow occurred.

Conditional jumps (if, while, for in C) test these flags. A comparison a == b is really "subtract and look at Z".

The instruction cycle

The CPU repeats a loop forever, billions of times a second on a fast chip, thousands of times a second on a slow one:

flowchart LR
    F["Fetch<br/>read instruction at PC"] --> D["Decode<br/>what operation, which registers"]
    D --> E["Execute<br/>ALU, load/store, branch"]
    E --> W["Write back<br/>result to register or memory"]
    W --> N["PC = PC + size<br/>(or jump target)"]
    N --> F
  1. Fetch: read the instruction at the address in PC from flash.
  2. Decode: work out which operation and operands it names.
  3. Execute: the arithmetic logic unit (ALU) computes, or a memory access happens, or a jump is taken.
  4. Write back: store the result.

A C statement like c = a + b; may become: load a into R0, load b into R1, ADD R0, R0, R1, store R0 into c: four instructions. The compiler works hard to keep values in registers so most of those loads and stores disappear when you enable optimization.

Pipelines

Doing the four stages for one instruction before starting the next wastes hardware: while the ALU executes, the fetch unit sits idle. A pipeline overlaps the stages so that a new instruction starts every cycle, like an assembly line. Cortex-M0 uses a 3-stage pipeline; Cortex-M3/M4 a 3-stage pipeline with branch speculation; Cortex-M7 a 6-stage dual-issue pipeline. The price: when the CPU takes a branch, the instructions behind it in the pipeline are wrong and must be thrown away (a few cycles lost), which is why tight loops are costlier than straight-line code and why timing is not just "instruction count".

Cycles, not lines

Embedded engineers count clock cycles. At 16 MHz one cycle lasts 62.5 ns; a 16-bit multiply that takes 2 cycles costs 125 ns. Some cores have hardware multiply and divide (Cortex-M3 and up); on cores without them, a / b is a library function that may take hundreds of cycles. Before using a division in an interrupt handler, check what your chip does.

Build a tiny CPU

The best way to understand the cycle is to write one. This toy CPU has four registers, an accumulator style instruction set, a program counter and a Z flag. The program (a countdown from 5 to 0) is stored as an array of numbers, just like machine code in flash.

C A toy CPU: fetch, decode, execute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The for (;;) loop is the instruction cycle: fetch program[pc++], decode with switch, execute, repeat. JNZ writes a new value into pc: that is all a jump is. If you add a second LDI to change the start to 3, the output shortens accordingly.

Seeing the flags

C hides the flags, but you can reconstruct what they would be. The next program performs 8-bit additions and reports N, Z, C and V, which shows the difference between carry (unsigned overflow) and overflow (signed overflow). The same bits patterns can be both, depending on how you interpret them.

C Condition flags after an 8-bit addition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

0x7F + 0x01 gives 0x80: as unsigned that is 128 (correct, no carry), but as signed 127 + 1 became -128 (V = 1). The hardware sets both flags; which one your code cares about depends on the type you are using. This is exactly the reason signed overflow in C is undefined behavior while unsigned arithmetic wraps predictably.

Instruction sets: Thumb, AVR, RISC-V

Different families encode the same ideas differently. ARM Cortex-M uses Thumb-2, a mix of 16-bit and 32-bit instructions that keeps code small. AVR has 32 8-bit registers and mostly single-cycle instructions. RISC-V has 32 registers (x0 is always zero) and a strict load/store design. In all of them you will find: arithmetic, logic, shifts, loads and stores, branches, calls and returns, and a way to enter and leave interrupts.

You can see the compiler's output on real code with arm-none-eabi-objdump -d firmware.elf, or in an online compiler explorer. Reading a few lines of assembly now and then is a cheap, powerful debugging habit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the program counter (PC) contain?

    PC points at the next instruction. A jump simply writes a new value into it.
  2. 2. What is the stack pointer used for?

    SP points to the top of the stack where return addresses, saved registers and locals are pushed.
  3. 3. 0x7F + 0x01 in 8-bit signed arithmetic sets which flag?

    127 + 1 does not fit in a signed byte, so V is set. Unsigned, 128 fits, so there is no carry.
  4. 4. Why can a taken branch cost extra cycles on a pipelined CPU?

    Instructions fetched after the branch are on the wrong path and must be flushed, so the pipeline has to refill.

Summary

  • A CPU has registers (including PC, SP, LR and status flags) and runs the fetch-decode-execute cycle forever.
  • A jump is just writing a new address into the program counter; a return restores it from the link register or the stack.
  • Flags Z, N, C and V record the result of arithmetic and drive conditional branches.
  • Pipelines overlap stages; branches and memory waits cost extra cycles, so measure in clock cycles.
  • A toy CPU in C shows the whole cycle; real cores add more registers, instructions and pipelines.

Next: Memory Types in a Microcontroller