Panel For Example Panel For Example Panel For Example

Common C Techniques for STM32 Development

Author : Adrian September 18, 2025

1. Bit operations

Bit operations are different from bit-banding. Bit operations operate on each bit of a variable, while logical bit operations operate on the variable as a whole.

Below are six common operators:

Bitwise NOT

void test01()
{
  int num = 7;
  printf("~num = %d\n", ~num);//-8
}

Bitwise AND

void test02()
{
  int num = 128;
  if ( (num & 1) == 0)
  {
    printf("num is an even number\n");
  }
  else
  {
    printf("num is an odd number\n");
  }
}

Bitwise XOR

void test03()
{
  num01 = 1; // 0001
  num02 = 4; // 0100
  printf("num01 ^ num02 = %d", num01 ^ num02); // 5
}

Bitwise OR

void test04()
{
  int a = 6; // binary 0110
  int b = 3; // binary 0011
  int c = a | b; // a and b bitwise OR, result 8, binary 111, assigned to c
}

Left shift

void test05()
{
  int num = 6;
  printf("%d\n", num << 3);
}

Right shift

void test06()
{
  int num = 6; // 0110
  printf("%d\n", num >> 1); // outputs 3
}

The above are ordinary C code examples. Below are code snippets commonly used in STM32:

(1) For example, to change the state of GPIOA->BSRRL, you can first clear parts of the register value using an AND operation

GPIOA-> BSRRL &= 0xFF0F;

Then use a bitwise OR to set the required value:

GPIOA-> BSRRL |= 0x0040;

(2) Use shift operations to improve code readability:

GPIOx->ODR = (((uint32_t)0x01) << pinpos);

(3) Example using bitwise NOT:

TIMx->SR = (uint16_t)~TIM_FLAG;

TIM_FLAG is defined via macros:

#define TIM_FLAG_Update ((uint16_t)0x0001)
#define TIM_FLAG_CC1 ((uint16_t)0x0002)

2. #define macros

#define is a preprocessor directive in C used for macro definitions. It can improve source code readability and assist programming.

Common form:

#define identifier string

Based on the above, here is a simple struct example:

struct sutdent
{
  int num;
  char name[20];
  char sex;
  int age;
  float score;
  char addr[30];
};

To define struct variables, you can declare them directly when defining the struct, or define the struct first and then declare variables, for example:

struct sutdent student01,student02;