.

INCLUDES RFID interfacing with avr GPS interfacing with avr RF Module interfacing with avr Stepper Motor With AVR

Tuesday, December 20, 2011

Assembler Basics

Assembler is a low-level language which does not know any C-like commands like for{;;} or while{}.
Assembler instructions are small, for example out PortD, r15 writes the contents of register 15 (which in an AVR can hold one byte) to PortD (which is 8 I/O lines handled as one I/O register).
Other assembler instructions only work on the register rather than on registers AND I/O registers or SRAM. "inc r15" is one of them. It increments the value register 15 holds by one. This is useful for loops (like for{;;}).
Almost every instruction leaves certain bits in the Status Register set or cleared based on the instruction's result. These bits can be used by branch instructions or arithmetic instructions in order to perform correctly (branch/don't branch, increment result etc).
Branch instructions jump to a specific code address (or code line) if the microcontroller is in a specific state or just go on with the next code line if this state is not present. If the counting variable in a loop has not reached the desired value, they can let the mcu repeat the loop.
Here is a small example code snippet showing how arithmetic, I/O and branch instructions work together:
ldi r16, 0
for_loop:
inc r16
out PortD, r16
cpi r16, 10
brlo for_loop
; load register 16 with zero
; this is a label we can jump or branch to
; increment register 16
; write contents of r16 to PortD
; compare value in r16 with 10 (this leaves a status for brlo)
; if value 10 not reached, repeat loop
In the loop the counter (r16) is increased in every iteration and written to PortD. When it reaches 10, brlo will not jump to the beginning of the loop, but to the next instruction. This small example gives a good impression of how small the steps you can take in assembler are. It can't get smaller, as this is what the mcu does. None of the instructions will be split into smaller ones by the assembler. With the comments in mind have a look at the AVR instruction set and also have a look at other instructions of the same type.
Assembler is very sensitive to programming errors. Try the above example with the increase instruction and the compare instruction swapped. What happens? The first value on PortD is 0, the last one is 9.
Now have a look at the "Flow Charts" section and try to write a flow chart of the code above. You'll see that flow charts make code less "cryptic" and readable. And keep them up to date every time you make a big enhancement to your code so that you can still read it after two weeks. Comments are also very important, especially if you can't make a flow chart every time your code changes. In assembler, a comment can be written for almost every line of code, especially when tricks are used.

No comments:

Post a Comment