close

Bit banding

The Cortex™-M3 memory map includes two bit-band regions. These regions map each
word in an alias region of memory to a bit in a bit-band region of memory. Writing to a word
in the alias region has the same effect as a read-modify-write operation on the targeted bit in
the bit-band region.
In the STM32F10xxx both peripheral registers and SRAM are mapped in a bit-band region.
This allows single bit-band write and read operations to be performed. The operations are
only available for Cortex-M3 accesses, not from other bus masters (e.g. DMA).
A mapping formula shows how to reference each word in the alias region to a corresponding
bit in the bit-band region. The mapping formula is:
bit_word_addr = bit_band_base + (byte_offset x 32) + (bit_number × 4)
where:
bit_word_addr is the address of the word in the alias memory region that maps to the
targeted bit.
bit_band_base is the starting address of the alias region
byte_offset is the number of the byte in the bit-band region that contains the targeted bit
bit_number is the bit position (0-7) of the targeted bit.
Example:
The following example shows how to map bit 2 of the byte located at SRAM address
0x20000300 in the alias region:
0x22006008 = 0x22000000 + (0x300*32) + (2*4).
Writing to address 0x22006008 has the same effect as a read-modify-write operation on bit
2 of the byte at SRAM address 0x20000300.
Reading address 0x22006008 returns the value (0x01 or 0x00) of bit 2 of the byte at SRAM
address 0x20000300 (0x01: bit set; 0x00: bit reset).
For more information on Bit-Banding, please refer to the Cortex™-M3 Technical Reference
Manual.

 

由上得知, peripheral registers也有提供bit-band的功能.

Example:

對GPIOD->ODR |= 0x00040;  //一般我們對GPIOD的第7個bit寫1

對GPIOD->ODR&= (~0x00040);  //一般我們對GPIOD的第7個bit寫0

這樣比較麻煩, 而且不直觀, 所以我們只要找出GPIOD->ODR第7個bit的位置就能直接讀寫.

GPIOD的位置是 0x40011400, ODR的offset是12, 所以GPIOD->ODR的位址是0x4001140C

peripheral registers bit-band region 是從0x42000000開始, 套上上面的公式

0x42000000 + (0x11400*32) + (7 * 4) = 0x4222801C

透過底下的假指令, 可以更輕鬆達成:

#define BITBAND(addr, bitnum) ((addr & 0xF0000000)+0x2000000+((addr &0xFFFFF)<<5)+(bitnum<<2))
#define MEM_ADDR(addr) *((volatile unsigned long *)(addr))
#define BIT_ADDR(addr, bitnum) MEM_ADDR(BITBAND(addr, bitnum))

#define GPIO_OUT_7    BIT_ADDR(0x4222801C, 7)    

那以後可以直接使用以下方式, 效果跟上面GPIO->ODR一樣.
GPIO_OUT_7    = 1;
GPIO_OUT_7    = 0;

 

 

arrow
arrow
    文章標籤
    STM32 Bit banding
    全站熱搜

    bear0626 發表在 痞客邦 留言(0) 人氣()