Bit Banding in ARM Cortex-M: What It Is and How It Works
bit-band alias addresses.How It Works
Bit banding works by creating a special alias memory region that corresponds to each bit in a defined memory area, such as SRAM or peripheral registers. Imagine you have a large wall of switches (bits) and a control panel where each switch can be toggled individually. Bit banding gives you a direct button for each switch, so you can turn it on or off without affecting others.
When you write to a bit-band alias address, the hardware automatically sets or clears the corresponding bit in the original memory. Reading from the alias address returns the bit's value as either 0 or 1. This mechanism avoids the need for read-modify-write sequences, making bit-level operations atomic and faster.
Example
This example shows how to set and clear a single bit in SRAM using bit banding on an ARM Cortex-M processor.
/* Base addresses for SRAM and its bit-band alias region */ #define SRAM_BASE 0x20000000 #define SRAM_BB_BASE 0x22000000 /* Macro to calculate bit-band alias address for a bit in SRAM */ #define BITBAND_SRAM(addr, bit) ((SRAM_BB_BASE + ((addr - SRAM_BASE) * 32) + (bit * 4))) volatile uint32_t *bit_alias; int main() { uint32_t *p = (uint32_t *)SRAM_BASE; // Pointer to SRAM start /* Set bit 3 of the first word in SRAM */ bit_alias = (uint32_t *)BITBAND_SRAM((uint32_t)p, 3); *bit_alias = 1; // Set bit 3 /* Clear bit 3 of the first word in SRAM */ *bit_alias = 0; // Clear bit 3 return 0; }
When to Use
Bit banding is useful when you need to change or read individual bits in memory or peripheral registers without affecting other bits. It is especially helpful in embedded systems where atomic bit manipulation is critical for interrupt-safe code and hardware control.
Common use cases include toggling GPIO pins, managing flags or status bits, and controlling hardware peripherals efficiently without complex locking or masking operations.
Key Points
- Bit banding maps each bit in a memory region to a separate 32-bit word in an alias region.
- It allows atomic bit-level read and write using normal 32-bit instructions.
- Reduces code complexity and improves performance for bit manipulation.
- Available on ARM Cortex-M3, M4, and M7 processors.
- Works for SRAM and peripheral memory regions with defined bit-band areas.