AVR Tutorials
The Best AVR Microcontroller Tutorials on the Web

Writing Macros for the AVR Assembler

Tutorial Objectives

After completing this AVR microcontroller tutorial readers should be able to:
  • Give a definition for the term macro.
  • Write an assembly macro.
  • Discuss the usefulness of macros.

Assembly Macros

What is a Macros?

In assembly programming a macro is basically a set of instruction represented by a single statement. A macro can be seen as a new instruction created by the programmer for the microcontroller.

Note however that this new instruction (the macro) is created by using the existing instructions that are provided with the AVR microcontroller.

Use of an Assembly Macros

Lets say you wanted to initialize the AVR stack pointer. It would take four (4) instructions to accomplish this task as shown in the AVR assembly code below. Here we are loading the last address of SRAM in the AVR microcontroller stack pointer.
                ;Initialize the AVR microcontroller stack pointer
                LDI    R16, low(RAMEND)
                OUT    SPL, R16
                LDI    R16, high(RAMEND)
                OUT    SPH, R16

Now instead of writing the four (4) instruction to initialize the AVR stack pointer you can define a macro, say LSP, with these instructions and use this macro to replace the set of instruction as shown in the AVR assembly code below.

                ;Initialize the stack
                LSP   R16, RAMEND

Steps in written AVR assembly macros

Macros are simple to code, as show in the code sample below, just follow the simple steps given here:
  1. All macros definitions starts with the MACRO assembler directive followed by the name of the macro in the same line. Here the name of our macro is LSP.
  2. Notice in macro definition below the @0 and @1 symbols. These are place holders for arguments that will be passed to the macro, @0 and @1 will be replaced by the first and second arguments respectively. Note you could also have @2, @3 and so on.
  3. Use the ENDMACRO AVR assembler directive to end the definition of your macro.
.MACRO        LSP
              LDI    @0, low(@1)
              OUT    SPL, @0
              LDI    @0, high(@1)
              OUT    SPH, @0

Once you have defined your macro it can be used just like any other of the AVR microcontroller instructions. Below shows how you would use the macro just define above. Note here that @0 and @1 will be replaced by R16 and RAMEND respectively in the macro definition.

                LSP   R16, RAMEND

AVR Tutorials hopes this assembly tutorial on writting AVR assembly macros was beneficial to you and looks forward to your continued visits for all your microcontroller tutorial needs.