ccpu-registersspibaud-rate

SPI and writing data to registers


How can I set multiple bits to 0 in C when working with CR registers with SPI?

I know that for setting individual bits I do:

SPI1->CR1 |= (1<<2); // To set bit 2
SPI1->CR1 &= ~(1<<7); // To reset bit 7

Context: I am setting a prescaler for the baud rate. In my case the prescaler is 2 and the binary value assigned to it according to the datasheet is 000. How can I assign bits 3-5 to 000?

Will it be

SPI1->CR1 &= ~(1<<3);

?

In the video I am following the guys does: SPI1->CR1 |=(3<<3), but he uses 011. He has a different microcontroller, thus the difference.


Solution

  • You can define your own (multi-bit) bit patterns without needing to shift:

     #define BITS_543 0x38 // == 0b0...111000
    

    (May as well express the set bits in left-to-right order in the name)

    To clear those bits you ask about:

     SPI1->CR1 &= ~BITS_543;
    

    The name you chose can even be more functional; eg "BAUD_RATE_TRIO"

    Give that a try...