Ground Embedded KO Subscribe

Notes / Machine Code & Assembly

What one instruction really is

Machine code is the numbers the CPU reads, and assembly is the names given to those numbers. See how many numbers one line of C becomes.

GROUND EMBEDDED · NOTEMachine Code & Assembly 01What an instruction is 1ldr r0, =0x40020014 2ldr r1, [r0] 3orr r1, r1, #0x20 4str r1, [r0] 5bl main 6b .

Firmware stored in Flash is, in the end, a list of numbers. The CPU reads these numbers one at a time and decodes "which operation, on which registers".

C:           x = x + 1;
Assembly:    adds r3, r3, #1
Machine code: 0x1C5B

Inside the 16-bit number 0x1C5B, "add, immediate 1, from register r3 to r3" is packed bit by bit. An assembler turns names into numbers and a disassembler turns numbers into names.

Ca = b + 1;AssemblyADDS r0, r1, #1Machine codea 16-bit numberCPU executes
From one line of C to the number the CPU reads.

Kinds of instruction

MoveMOV, LDR, STRCalculateADD, SUB, ANDCompareCMPBranchB, BL, BX
Instructions do four broad kinds of work.
Kind Examples What it does
Data processing add, sub, and, lsl Calculate between registers
Memory access ldr, str Memory ↔ register
Branch b, bl, bx Move the flow of execution
Compare cmp Set the flags

ARM is a load-store architecture: it cannot calculate on a memory value directly. It must load it into a register (ldr), calculate, and store it back (str). That is why the single C line count++ becomes three instructions.

Why you need to know

When following a hard-fault address, understanding a race on a variable shared with an interrupt, or shortening a control loop, you have to look at the instructions the compiler produced.

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →