STM32 L1 Tutorial #2: Boost your code (Bit-Banding)

stm32_icon_bigToday I’m going to show you how to speed things up in your code by using marvelous feature called “Bit-Banding”. Basically bit-banding is a new way of addressing (and accessing) things in some parts of your Cortex-M3 uC address space. Well, you would probably ask if there is any room for any useful improvement in such simple and straightforward thing as addressing. Actually, there is.

Remember those moments when you tried to access and change value of separate bits in registers? It always involved three operations: read-update-write. Read operation was just to copy full register value to temporary variable, update was either ‘logical AND’ or ‘logical OR’ to clear or set bit of your interest respectively, and finally a write to update register’s value. As one can see, lots of computing power is involved in such simple thing as bit’s value altering. Bit-banding removes all that overhead by giving you the possibility to access register bits as separate memory locations. Neat!

Accessing bits as they were words!

To be able to access register bits with bit-banding programmer must locate that bit’s memory location. According to STM32L Reference Manual mapping is done by this formula:

bit_word_addr = bit_band_base + (byte_offset * 32) + (bit_number * 4)

where:

  • bit_band_base – a constant that indicates which memory area you are trying to access. For SRAM bits use 0x2200 0000, for peripheral registers use 0x4200 0000.
  • byte_offset – this is a byte offset of register that you are trying to access. Offset is derived from actual address minus starting address of its memory section. Example 1: byte_offset of SRAM (SRAM starts at 0x2000 0000) variable located at 0x2000 0100 is 0x2000 0100 – 0x2000 0000 = 0x0000 0100. Example 2: byte_offset of GPIOA->ODR (address: 0x4002 0014) register is 0x0002 0014, since peripheral memory section starts at 0x4000 0000.
  • bit_number – just the number of bit you are trying to map. Plain and simple.

Accessing bits as they were words! With my lib!

Using bit-banding wouldn’t be that much fun if you had to use and compute above’s formula value all the time, but hey, that’s what libraries are for. Mine does it all for you, with simple macros.

Last time (Tutorial #1) we were experimenting with GPIO pin that was used to drive LED. Let’s see how it could be done with bit-banding.

/* system entry point */
int main(void)
{
	/* gpio init struct */
	gpio_init_t gpio;

	/* reset rcc */
	RCC_DeInit();

	/* enable clock to GPIOC */
	RCC_AHBPeriphClockCmd(AHB_GPIOC, ENABLE);

	/* initialize gpio structure */
	GPIO_StructInit(&gpio);
	/* use pin 13 */
	gpio.pins = GPIO_P13;
	/* mode: output */
	gpio.mode = GPIO_OUTPUT;
	/* output type: push-pull */
	gpio.otype = GPIO_OT_PP;
	/* apply configuration */
	GPIO_Init(GPIOC, &gpio);

	/* bit-band definition */
	bitband_t pin = BITBAND_PERIPH(&GPIOC->ODR, 13);

	/* main program loop */
	for (;;) {
		/* set led on */
		*(pin) = 1;
		/* clear led */
		*(pin) = 0;
	}

	/* never reached */
	return 0;
}

Here (line #25) we have defined variable of type bitband_t which now represents bit 13 in GPIOC ODR (Output Data Register). bitband_t is a pointer to mapped memory location, so writing/reading values is done in a ‘pointer-ish’ way, with use of ‘*’ operator.  Simple as that. Using bit-banding with SRAM bits is very similar:

	uint32_t sram_flags;
	/* bit-band definition */
	bitband_t sram_flags_bit_0 = BITBAND_SRAM(&sram_flags, 0);
	/* change value */
	for (;;) {
		*(sram_flags_bit_0) = 1;
		*(sram_flags_bit_0) = 0;
	}

Pros and Cons.

As it was mentioned before bit-banding speeds things up. By what factor? Well, it will probably depend on whole context, but one can easily find many different use-cases that are perfectly tailored for this technique, such as:

  • Clearing Interrupt status bits – saves you some cycles during interrupt routine execution
  • Fast GPIO toggling – pretty much explains itself, useful when implementing bit-banging (with ‘G’ :) ) interfaces
  • Preemption safe bit value changing – no read-update-write, just write, good for dealing with data that is processed by interrupt routines and main program loop simultaneously.

In above’s example frequency of LED toggling with bit-banding as opposed to GPIO_SetPin(), GPIO_ClearPin() increased by over 170% (was 96kHz, is 262kHz, using Os level of GCC optimization, 1MHz MSI clock (default one)). Definitely worth the effort!

There are some situations that make the use of bit-banding not practical. Those include:

  • Complex Initialization – things done only once per device’s power cycle, like GPIO inits. Using bit-banding there makes hard code hard to read and debug.
  • Updating multiple bit fields in registers – many of those exist, updating those bits one-by-one may lead to unwanted (and, in some cases, even unpredictable) device’s behavior.

Limitations

Two that I am aware of. Bit-banding is available only for SRAM and Peripheral section, so no funny business operations in FLASH. Bit-banding  accesses are only legit if done by Cortex-M3 core itself. What that means is, that you cannot use DMA transfers to bit-band memory locations.

Files

STM32 L1 Tutorial #1: Hello, World! (LED Blink)

stm32_icon_bigToday I’m about to show you how to make any use of my version of STM32L Standard Peripheral Library (post, .zip). First order of business for everyone that starts using MCU that he never used before is to get into controlling states of MCUs General Purpose Input/Output (GPIO) pins which translates to setting the voltage high or low on those pins. This can (and will) be used to lit up a LED directly connected to leads of our STM32L. I am assuming that reader has some basic knowledge about C Programming language, because I’m not planning to describe every line in every file, but to focus on what’s important. Here’s the code that does all that magic:

/* system entry point */
int main(void)
{
	/* gpio init struct */
	gpio_init_t gpio;

	/* reset rcc */
	RCC_DeInit();

	/* enable clock to GPIOC */
	RCC_AHBPeriphClockCmd(AHB_GPIOC, ENABLE);

	/* initialize gpio structure */
	GPIO_StructInit(&gpio);
	/* use pin 13 */
	gpio.pins = GPIO_P13;
	/* mode: output */
	gpio.mode = GPIO_OUTPUT;
	/* output type: push-pull */
	gpio.otype = GPIO_OT_PP;
	/* apply configuration */
	GPIO_Init(GPIOC, &gpio);

	/* main program loop */
	for (;;) {
		/* set led on */
		GPIO_SetPins(GPIOC, GPIO_P13);
		/* delay */
		simple_delay(100000);
		/* clear led */
		GPIO_ClearPins(GPIOC, GPIO_P13);
		/* delay */
		simple_delay(100000);
	}

	/* never reached */
	return 0;
}

Preparing the MCU

First step when you are dealing with STM32L will be resetting the RCC, which is done in line #8. RCC is that little MCU fragment that is responsible for enabling/disabling clock to all other modules, such as GPIO, as well as controlling MCU clock speed. After a reset we need to bring it to a known state and that’s why we call RCC_Deinit() routine.

Configuring GPIO

In order to be able to use GPIO port (MCU pins are grouped in ports, every port can have up to 16 pins) we need to enable it’s clock. It is a common pitfall to forget about enabling particular peripheral’s clock, so keep in mind that this should be the first step before using any of peripheral’s registers.

Since we’ve got our GPIO up and running, we need to configure the operation of pin that will drive our LED. This is accomplished with the use of gpio_init_t structure. First thing that should be done here is to reset it’s contents by calling GPIO_StructInit() which will set all fields to their default values. Why bother using this function? Well, since our struct is stored on stack (it is defined inside main() function, not as a global variable) it will contain rubbish values, because stack variables aren’t initialized just as global variables are. Several fields of that data structure have been used to define pin’s behavior:

  • gpio.pins – selects which pin we are about to configure. In this case it’s pin 13.
  • gpio.mode – chooses pin mode of operation, which can be input, output, alternate function (pin driven by some other peripheral) or analog (pin used by analog to digital converter), in this case, since we want to *drive* LED we need to go for GPIO_OUTPUT.
  • gpio.otype – output pins can operate in two modes: push-pull (MCU can set pin high and low) or open-drain (MCU can set pin low and high-impedance). We choose push-pull mode to be able to set pin high.

After setting all the fields we need to apply this configuration to given port. My LED is connected to pin PC13, I used GPIO_Init() with the first argument set to GPIOC.

Using GPIO pin

Now the eye-candy. I have written a simple loop (lines 25 – 34) that will turn-on and turn-off the LED just to demonstrate that this tutorial actually does something. As you can see the simplest way of altering pin output states is to use GPIO_SetPin() and GPIO_ClearPin() respectively. I have also inserted some wait-sates just so the LED doesn’t blink too fast.

Files

  • Source Code – all that you need to run this example, just compile, upload to your mcu and observe the magic!