The application of register bit operation in STM32

Recently I was learning I2C communication, and I found that there were two lines of code that I couldn’t understand (because the [library functions] I have been using all the time , I did not use the bit operation), the code is:

# define SDA_IN() {GPIO->CRL&=0x0FFFFFFF;GPIOB->CRL|=(u32)8<<28)} //pull-up input

# define SDA_OUT() {GPIO->CRL&=0x0FFFFFFF;GPIOB->CRL|=(u32)3<<28)} //Push-pull output

First of all, the SDA pin used by I2C is PB7. When the clock is enabled, there are two GPIOB->CRL and GPIOB->CRH. The meaning of 32 in STM32 is that the [registers] are 32-bit (not both), and for CRL and CRH registers, both are 32-bit registers.
Look at the code next

# define SDA_IN() {GPIO->CRL&=0x0FFFFFFF;GPIOB->CRL|=(u32)8<<28)} //pull-up input

First of all, let’s mention the conversion relationship between hexadecimal and binary : in hexadecimal, each hexadecimal corresponds to 4-bit binary. For example, the binary corresponding to 0xFF is 1111 1111, and 0xAF corresponds to 1010 1111. One-to-one correspondence is Can.

The meaning in the code GPIO->CRL&=0x0FFFFFFFis: clear the bit of PB7 that needs to be used to facilitate subsequent initialization. GPIOB->CRL|=(u32)8<<28)It is to perform [bit operation]8<<28)It is to perform [bit operation] on 28:31 bits, because to achieve pull-up input, according to the relevant register configuration, 28:29 bits should be set to 00, 30:31 bits should be set to 10, then the 28:31 bit register bit is It is 1000, which corresponds to 8 in decimal, so 8 (that is, 1000) should be written into 28:31 bits. In STM32, u32 is unsigned int (unsigned integer type), (u32)8 forces 8 to be converted to an integer type, and the calculation is as follows:</p> <p>0000 0000 0000 0000 0000 0000 0000 1000<br /> left-shift 28 bits<br /> -----------------------> get:<br /> 1000 0000 0000 0000 0000 0000 0000 0000</p> <p>Then through <code>GPIOB->CRL|=(u32)8<<28)</code>the bit OR operation:<br /> 1000 0000 0000 0000 0000 0000 0000 0000 |<br /> 0000 (0-27 bits are the initial amount)<br /> =1000 (0-27 bits remain unchanged)</p> <p>***Bit operation review: 1|any=1; 0&any=0</p> <p>That is, through bit operation, the PB7 working mode is realized as a pull-up input.<br /> Similarly push-pull output:</p> <pre><code> # define SDA_OUT() {GPIO->CRL&=0x0FFFFFFF;GPIOB->CRL|=(u32)3<<28)} //Push-pull output`

Reverse push: 3 represents binary 0011, corresponding to general push-pull output in 50MHz output mode.

If there are any mistakes in writing, please correct me!

Leave a Comment

Your email address will not be published. Required fields are marked *