Home / Learn Chip Programming / Inline Assembly and Intrinsics
Inline Assembly and Intrinsics
Sometimes you need one special instruction: wait for interrupt, disable interrupts, byte swap.
Theory in plain words
What it is
GCC extended asm embeds assembly in C with input/output constraints. Intrinsics (CMSIS: __WFI, __disable_irq, __REV) are safer wrappers.
Why we use it
Some instructions have no C equivalent. Exact timing, atomic sections and special registers need them.
How it works
Prefer intrinsics. If you write asm, declare outputs, inputs and clobbers so the compiler keeps its registers consistent.
Where it is used
- Entering sleep (WFI)
- Interrupt control, memory barriers
- Fast bit tricks (CLZ, REV, SSAT)
Common instructions
static inline void wait_for_interrupt(void) { __asm volatile ("wfi"); }
static inline uint32_t primask_save(void) { uint32_t r; __asm volatile ("mrs %0, primask\n cpsid i" : "=r"(r) :: "memory"); return r; }
static inline void primask_restore(uint32_t r) { __asm volatile ("msr primask, %0" :: "r"(r) : "memory"); }
static inline uint32_t rev_bytes(uint32_t x) { uint32_t r; __asm volatile ("rev %0, %1" : "=r"(r) : "r"(x)); return r; }
// CMSIS: __WFI(), __disable_irq(), __enable_irq(), __REV(x), __CLZ(x), __NOP(), __DSB()ARM and AVR are little endian: the lowest byte is stored first. Network protocols are big endian, so you often swap.
Quick quiz
1. What does the WFI instruction do?
Core sleeps until an interrupt.
2. Why prefer intrinsics?
The compiler can schedule and check them.
Common questions
What does the WFI instruction do?
Waits for an interrupt (sleep). Core sleeps until an interrupt.
Why prefer intrinsics?
The compiler understands them. The compiler can schedule and check them.