ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 55

Inline Assembly in C

A few instructions inside a C program.

Most compilers let you embed assembly instructions in C source using an asm statement. It is useful for special instructions with no C equivalent, such as entering sleep mode or inserting a precise delay.

The compiler must be told which registers you change, or it may keep values in them. Syntax varies between compilers, so check yours.

Keep the assembly to one or two lines and wrap it in a named function.

EXAMPLE
/* generic form; exact syntax differs between compilers */
static inline void cpu_nop(void) {
    asm volatile("nop");   /* do nothing for one cycle */
}