9.1.7 Tip #7 Low Level Assembly Instructions

Well coded assembly instructions are always the best optimized code. One drawback of assembly code is the non-portable syntax, so it's not recommended for programmers in most cases.

However, using assembly macros reduces the pain often associated with assembly code, and it improves the readability. Use macros instead of functions for tasks that generates less than 2-3 lines assembly code. The table below shows the code usage of assembly macro compared with using a function.

Table 9-8. Example of Low Level Assembly Instructions
FunctionAssembly Macro
C source code
#include <avr/io.h>
void enable_usart_rx(void)
{
UCSR0B |= 0x80;
};
int main(void)
{
enable_usart_rx();
while (1){
}
}
#include <avr/io.h>
#define enable_usart_rx() \
__asm__ __volatile__ ( \
"lds r24,0x00C1" "\n\t" \
"ori r24, 0x80" "\n\t" \
 "sts 0x00C1, r24" \
 ::)
int main(void)
{
enable_usart_rx();
while (1){
}
}
AVR Memory Usage

Program: 90 bytes (1.1% Full)

(.text + .data + .bootloader)

Data: 0 bytes (0.0% Full)

(.data + .bss + .noinit)

Program: 86 bytes (1.0% Full)

(.text + .data + .bootloader)

Data: 0 bytes (0.0% Full)

(.data + .bss + .noinit)

Compiler optimization level-Os (Optimize for size)-Os (Optimize for size)

Refer to AVR-Libc User Manual for more details.