Investigating BSRR register (Bit Set Reset)

In this guide, we shall investigate why there is BSRR (Bit Set Reset Register) in STM32 to set/reset a specific GPIO pin.

In this guide, we shall cover the following:

  • Toggle pin with ODR and BSRR
  • Reason behind BSRR

1. Toggle pin with ODR and BSRR:

In out most guides, we are using ODR (Output Data Register) to toggle the LED. Take for example getting started with STM32L0 (Here) and with STM32F7 (here) to toggle the LEDs.

Mostly, we are using ODR to toggle the pin as following: (from STM32L0)

Set pin to high:

GPIOA->ODR |= GPIO_ODR_OD5;

Set pin to low:

GPIOA->ODR &=~ GPIO_ODR_OD5;

On another handle, to set pin high with BSRR:

GPIOA->BSRR= GPIO_BSRR_BS_5;

To set the pin low:

GPIOA->BSRR= GPIO_BSRR_BR_0;

You might ask, why both?

It comes in performance and what called race condition, take the following to screenshot for toggling the pin as fast as possible using both method.

toggle using ODR

toggle using BSRR

Take a look at the frequency, toggling the pin using BSRR is faster and almost has 50% duty cycle compared to ODR where you get low state longer than the high state.

2. Reason behind BSRR:

In order to toggle a pin using ODR, the MCU has perform the following three steps:

  • Read the register.
  • Modify the register.
  • Write back to the register.

Using BSRR, the MCU has to perform one step only which is:

  • Write the new value to the register.

This method allows the user to set the pin atomically.

 you simply perform a single 32-bit write to the BSRR to set or only the relevant bits.

This often means you don’t have to disable interrupts or use other concurrency protections when using the BSRR, and results in smaller and faster code for bit twiddling operations.

3. Digging deeper:

Check this video where the process of writing each pin using ODR individually and the process is being interrupt each 1 millisecond:

Note how the blinking interval is being inconsistent. This condition called race condition.

This happen when the toggle operation is getting interrupted.

This is fine for toggling LEDs since it won’t have catastrophic effect. In real time embedded systems, this might lead catastrophic problems. For example, a nuclear plant needs to be cooled down and the process get interrupted and lead to turn off the cooling system. This will have catastrophic consequences.

For that alone, chip manufacturers came up with BSRR (STM32) to avoid race condition.

Happy coding 🙂

Add Comment

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