Structure of an Assembly Language Program
Assembly language programs will look very different from the C programs you are used to. In assembly, lines are organized into columns for readability and will typically contain labels, directives, or instructions followed by zero, one or two operands. Some examples of assembly line structures are shown below.
inst op1,op2 ; a label, followed by an instruction with two operands inst op1 ; an instruction with one operand inst ; an instruction with no operands; a directive lbl1: arg ; a label followed by a directive with an argument lbl2:
Each of these items can be organized into any column the programmer chooses, although the order in which they appear matters. It is common practice to reserve the first column for labels and place instructions in the second or third.
Instructions are special mnemonics the assembler translates into machine code. As the name suggests, they instruct the microcontroller to do something.
Instructions may require one, two, or no operands which must immediately follow it on the same line. Below is an example of a microcontroller instruction with two operands.
add r16,r17 ; add r16 and r17
Note that the operands above must be separated by a comma. In addition, they are tabbed into the next column to make it easier to read.
Some instructions require only a single operand. For example
dec r16 ; decrement r16
A few instructions can be called with no operands.
sei ; enable global interrupts
Labels are not assembled into the final program but are used by the programmer to mark certain sections of the code with a meaningful tag. During assembly the label will be translated into a program address which can be used as a target for "jump" or "branch" instructions.
The below code shows an infinite loop where a label jmp is used to continuously "jump" to it:is defined. Then the instruction
here: jmp here
Labels can be placed on a line by themselves. The following is equivalent to the previous example.
here: jmp here
Since labels are not assembled into the final program, they do not affect addesses. They will simply mark the address of the first instruction that follows it.
When defining a label, it must be followed by a colon, but when used as an operand it is specified without the colon.
Like labels, directives are not part of the final program but are used as special instructions for the assembler. A common directive iswhich will copy the contents of a file into code.
Directives always begin with a period.
Comments in assembly begin with a semicolon. Comments will usually be placed in the rightmost column of a line of code like so
add r16,r17 ; add the contents of register 16 and 17
If you are using Atmel Studio, you can also use // and /* */ to denote comments, although this is not supported by some of the other assemblers.