Home / Learn Chip Programming / Assembly Language Basics
Assembly Language Basics
Assembly is the human readable form of machine code. One line equals one machine instruction.
Theory in plain words
What it is
Assembly language is a text form of machine code. Each line is one instruction, such as ADD R0, R1. An assembler converts it to the binary the CPU runs.
Why we use it
You read assembly to debug crashes, check what the compiler produced, write start-up code, and write tiny fast routines where C is too slow or too big.
How it works
You use registers, memory addresses, labels for jump targets and flags. Conditions are two steps: compare (sets flags), then branch (reads flags).
Where it is used
- Startup code and interrupt vectors
- Bootloaders and context switching in an RTOS
- Reverse engineering and security
- Hand optimised code (cryptography, DSP)
Pattern 1: a loop
ldi r16, 10 ; counter = 10
loop: dec r16 ; counter--
brne loop ; branch if not equal (Z flag is 0)
; falls through here after 10 roundsPattern 2: if / else
cpi r16, 5 ; compare a with 5 (sets flags)
brne else_part ; if not equal, jump
ldi r17, 1 ; then: x = 1
rjmp done
else_part:
ldi r17, 2 ; else: x = 2
done:Try it: edit the program
Change the numbers, then try to compute 3 + 2 + 1 or a countdown. There is no multiply instruction, so repeated addition does the job, just like early CPUs.
ARM Cortex-M example
LDR R0, =0x40010C0C ; address of the GPIO output data register (example)
MOV R1, #(1 << 13) ; bit mask for pin 13
loop: LDR R2, [R0] ; read the register
EOR R2, R2, R1 ; toggle the pin bit
STR R2, [R0] ; write it back
BL delay ; call a delay routine
B loopLDRloads from memory,STRstores to memory (ARM is load/store: arithmetic works only on registers).BLbranches and saves the return address in the link register LR.EORis exclusive OR, the toggle operation.
arm-none-eabi-gcc -S main.c or with the Compiler Explorer website. Reading it is the fastest way to learn.Quick quiz
1. What converts assembly into machine code?
The assembler does it.
2. How is a condition done in assembly?
CMP sets flags, a conditional branch reads them.
Common questions
What converts assembly into machine code?
Assembler. The assembler does it.
How is a condition done in assembly?
Compare to set flags, then branch. CMP sets flags, a conditional branch reads them.