ARM Technical Support Knowledge Articles

How can I use Cortex-M3 bit-banding from C code?

Applies to: RealView Development Suite (RVDS)


The Cortex-M3 processor has a feature known as "bit-banding." This allows an individual bit in a memory-mapped mailbox or peripheral register to be set/cleared by a single store/load instruction to a bit-banded, aliased memory address, rather than using a conventional read/modify/write instruction sequence.

There are no special compiler extensions to support this, but it is easy to write C macros to handle bit-banding in a straightforward way.

For example:

#define BITBAND_SRAM_REF   0x20000000
#define BITBAND_SRAM_BASE  0x22000000
 (a-BITBAND_SRAM_REF)*32 + (b*4)))  // Convert SRAM address
#define BITBAND_PERI_REF   0x40000000
#define BITBAND_PERI_BASE  0x42000000
 (a-BITBAND_PERI_REF)*32 + (b*4)))  // Convert PERI address

#define MAILBOX   0x20004000
#define TIMER     0x40004000
#define MBX_B0    *((volatile unsigned int *)
#define MBX_B7    *((volatile unsigned int *)
#define TIMER_B0  *((volatile unsigned char *)
 (BITBAND_PERI(TIMER,0)))   // Bit 0
#define TIMER_B7  *((volatile unsigned char *)
 (BITBAND_PERI(TIMER,7)))   // Bit 7

int main(void)
    unsigned int temp = 0;

    MBX_B0 = 1;      // Word write
    temp = MBX_B7;   // Word read
    TIMER_B0 = temp; // Byte write
    return TIMER_B7; // Byte read

The code generated for Cortex-M3 is:

main    LDR     r0,|L1.16|       // Pointer to MAILBOX
        MOVS    r1,#1
        STR     r1,[r0,#0]
        LDR     r0,[r0,#0x1c]
        LDR     r1,|L1.20|       // Pointer to TIMER
        STRB    r0,[r1,#0]
        LDRB    r0,[r1,#0x1c]
        BX      lr
|L1.16| DCD     0x22080000       // Bitband addr of MAILBOX
|L1.20| DCD     0x42080000       // BitBand addr of TIMER

Article last edited on: 2016-06-01 20:52:29

Rate this article

Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential