Topics / Embedded C / Q12
What is bit-banding on Cortex-M?
Short answer: On Cortex-M3 and Cortex-M4, bit-banding maps each bit of two 1 MB regions (the first 1 MB of SRAM at 0x20000000 and of the peripheral space at 0x40000000) to its own 32-bit word in an alias region (0x22000000 and 0x42000000). Writing 0 or 1 to an alias word changes exactly that one bit atomically (the bus does the read-modify-write in one locked transaction); reading the alias word returns the bit's value.
Address formula
alias_address = alias_base + (byte_offset × 32) + (bit_number × 4)
SRAM: alias_base = 0x22000000, byte_offset = address - 0x20000000
Peripheral: alias_base = 0x42000000, byte_offset = address - 0x40000000
Example: bit 5 of the register at 0x40020014 (GPIOA ODR on an STM32F4):
#define BITBAND_PERIPH(addr, bit) \
(*(volatile uint32_t *)(0x42000000u + (((uint32_t)(addr) - 0x40000000u) * 32u) + ((bit) * 4u)))
BITBAND_PERIPH(&GPIOA->ODR, 5) = 1; /* set PA5 atomically: 0x42000000 + 0x20014*32 + 20 = 0x42400294 */
Benefits
- Atomic set/clear of one bit without disabling interrupts.
- Faster than a software read-modify-write in some cases.
- Compact boolean flags in SRAM that can be updated from ISRs safely.
Limitations
- Only on Cortex-M3 and M4 (and only if the chip vendor implemented it). Not on Cortex-M0/M0+, M7, M23, M33, M55 or M85.
- Only the two 1 MB regions.
- Still a read-modify-write at the bus level: on registers with W1C bits or read side effects, it can have the same unwanted effects as a software RMW of the whole word.
Portable alternatives: hardware set/clear registers, exclusive access instructions, or critical sections. Because bit-banding was removed from newer cores, new code should not depend on it.