The bit-banding operation of the STM32 microcontroller is a special memory mapping technique that allows developers to perform atomic read and write operations on specific memory bits, thereby improving the efficiency of operations on GPIO ports, registers, and individual bits of other peripherals.
1. Bit-Band Region and Bit-Band Alias Region
The memory space of the STM32 microcontroller is divided into a bit-band region and a bit-band alias region. The bit-band region includes the lowest 1MB of the SRAM area (address range 0x2000_0000-0x200F_FFFF) and the lowest 1MB of the on-chip peripheral area (address range 0x4000_0000-0x400F_FFFF). The bit-band alias region maps each bit in the bit-band region to a 32-bit word, achieving a transition from byte addressing to bit addressing.
2. Address Mapping RelationshipEach word in the bit-band alias region corresponds to a bit in the bit-band region. The mapping formula is: bit_word_addr = bit_band_base + (byte_offset × 32) + (bit_number × 4). bit_word_addr: the address of the word in the alias memory region. bit_band_base: the starting address of the alias region (the starting address of the SRAM bit-band alias region is 0x22000000, and the starting address of the peripheral bit-band alias region is 0x42000000). byte_offset: the index of the byte containing the target bit in the bit-band region. bit_number: the position of the target bit (0-31).
3. Advantages of Bit-Banding OperationsIt improves code readability and execution efficiency, especially when operating on individual bits of GPIO ports and registers. It achieves atomic operations, avoiding race conditions and data inconsistency issues that may arise in multithreaded or interrupt environments. It simplifies operations on hardware I/O-intensive low-level programs and the management of system programs that use bit flags extensively.
4. Bit-Banding Operations in C Language
In C language, macros are used to implement bit-banding operations. By defining macros that convert “bit-band address + bit number” into alias addresses, and macros that convert alias addresses into pointer types, bit-banding operations can be conveniently performed in C code. Example macro definitions: #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))
Use the volatile keyword to define the variable to be accessed to ensure that the compiler writes the new value to memory each time.
This is an original article by Fan Yi Enterprise Training, please indicate the source when reprinting!
Submission/Recruitment/Advertisement/Course Collaboration/Resource Exchange; please add WeChat: 13237418207