Ground Embedded KO Subscribe

Notes / Machine Code & Assembly

Reading Thumb instructions

Read the MOV, LDR, STR, B and BL that appear most in the Thumb instruction set used by Cortex-M, with real disassembly examples.

GROUND EMBEDDED · NOTEMachine Code & Assembly 02Reading Thumb instructions 1ldr r0, =0x40020014 2ldr r1, [r0] 3orr r1, r1, #0x20 4str r1, [r0] 5bl main 6b .

Cortex-M uses only Thumb-2, a mix of 16-bit and 32-bit instructions. Its advantage is small code size.

Instructions you see often

Instruction Meaning
movs r0, #5 r0 = 5
ldr r1, [r0] r1 = the memory value r0 points to
ldr r1, [r0, #4] r1 = *(r0 + 4)
str r1, [r0] Store r1 in the memory r0 points to
orr r1, r1, #32 r1 |= 0x20
cmp r0, #10 Compare r0 with 10, set the flags
bne label Go to label if not equal
bl func Call func (return address goes in lr)
bx lr Return from a function
push {r4, lr} / pop {r4, pc} Save registers / restore them and return

Try reading

LDR r0, [r1]memory → registerADDS r0, #1calculate in the registerSTR r0, [r1]register → memory
Three lines that read a value from memory, add 1 and store it back.
ldr   r3, =0x40020014   ; address of GPIOA_ODR
ldr   r2, [r3]          ; read the current value
orr   r2, r2, #0x20     ; set bit 5
str   r2, [r3]          ; write it back

This is GPIOA->ODR |= (1 << 5); in C. At instruction level you can see that if an interrupt changes the same register between the read and the write, that change is lost.

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 →