A Guide to Common STM32 Microcontroller Concepts

STM32 microcontrollers are powerful ARM Cortex-M-based MCUs commonly used in embedded systems development. This article provides an in-depth overview of 16 key concepts related to working with STM32, including the startup process, GPIO configuration, standard communication protocols like UART, I2C, and SPI, advanced features like DMA and interrupts, RTOS task scheduling, and version control with Git. Whether you are just getting started with STM32 or looking to expand your knowledge, this guide will walk you through the fundamentals and clarify how to leverage the capabilities of these versatile microcontrollers. Core topics span from initializing the critical system clock sources to leveraging interrupts and DMA for efficient data transfer, implementing inter-task communication and synchronization with RTOS primitives like semaphores and message queues, and best practices for collaborating on STM32 projects using Git version control. This comprehensive introduction covers practical STM32 application development from initial setup to utilizing key peripherals, communication protocols, and RTOS features through hands-on examples.

1. What are the differences between STM32F1 and F4?

Different cores: F1 is Cortex-M3 core, F4 is Cortex-M4 core;

Different main frequencies: F1 main frequency 72MHz, F4 main frequency 168MHz;

Floating point operations: F1 has no floating point unit, F4 has;

Functional performance: F4 peripherals are richer and more powerful than F1, such as GPIO toggle rate, pull-up/pull-down resistor configuration, ADC accuracy, etc;

Memory size: F1 internal SRAM max 64K, F4 has 192K (112+64+16).

2. Introduction to the STM32 startup process

Set initial address through Boot pin;

Initialize stack pointer __initial_sp;

Point to reset program Reset_Hander;

Set exception interrupt HardFault_Handler;

Set system clock SystemInit;

Call C library function _main.

3. Introduction to GPIO

GPIO 8 working modes (gpio_init.GPIO_Mode):

(1) GPIO_Mode_AIN Analog input

(2) GPIO_Mode_IN_FLOATING Floating input

(3) GPIO_Mode_IPD Pull-down input

(4) GPIO_Mode_IPU Pull-up input

(5) GPIO_Mode_Out_OD Open drain output

(6) GPIO_Mode_Out_PP Push-pull output

(7) GPIO_Mode_AF_OD Alternate function open drain output

(8) GPIO_Mode_AF_PP Alternate function push-pull output

APB2 is responsible for AD, I/O, advanced TIM, UART1.

APB1 is responsible for DA, USB, SPI, I2C, CAN, UART2345, ordinary TIM, PWR.


Q1: Introduction to serial communication methods

Synchronous communication: I2C half duplex, SPI full duplex;

Asynchronous communication: RS485 half duplex, RS232 full duplex.

Q2: UART configuration

UART configuration general steps can be summarized as:

(1) Enable UART clock, enable GPIO clock;

(2) UART reset;

(3) Set GPIO port mode;

TX GPIO mode: GPIO_Mode_AF_PP; //Alternate function push-pull output

RX GPIO mode: GPIO_Mode_IN_FLOATING; //Floating input

(4) Initialize UART parameters mainly including: baud rate (115200), 8 data bits, 1 stop bit, no parity, no hardware flow control, transmission mode.

(5) Enable interrupt and initialize NVIC (if interrupt enabled);

(6) Enable UART;

(7) Write interrupt handler.

Q3: Main features of USART

(1) Full duplex operation (independent receive and transmit data);

(2) Synchronous operation, clock can be master or slave;

(3) Independent high precision baud rate generator, does not occupy timer/counter;

(4) Supports 5, 6, 7, 8 and 9 data bits, 1 or 2 stop bits frame structure;

(5) Hardware supported parity generation and check;

(6) Data overflow detection;

(7) Frame error detection;

(8) Including error start bit detection, noise filter and digital low pass filter;

(9) Three completely independent interrupts: TX complete, TX data register empty, RX complete;

(10) Supports multi-processor communication mode;

(11) Supports double speed asynchronous communication mode.

Application scenarios: GPS, Bluetooth, 4G modules.

5. I2C

Q1: I2C bus has three types of signals during data transfer

(1) Start signal: SCL is high, SDA jumps from high to low, start data transfer.

(2) Stop signal: SCL is high, SDA jumps from low to high, stop data transfer.

(3) Acknowledge signal: after receiving 8bit data, the IC receiving data sends a specific low pulse to the IC sending data to indicate data received.

After the CPU sends a signal to the slave unit, it waits for the slave unit to send an acknowledge signal. If no acknowledge signal received, the CPU determines the slave unit is faulty.

Q2: How to configure I2C master mode ports

Hardware mode: Alternate function open drain, neither pull-up nor pull-down. (Fast mode: 400 Kbit/s)

Software simulation: Push-pull output, configure pull-up resistor.

Q3: I2C arbitration mechanism?

I2C arbitration mechanism is clear with understanding of Wired-AND. Simply put, it follows the “low level priority” principle, that is, whoever sends low level first will gain control of the bus.

Hardware mode: Set by communication baud rate

/* STM32 I2C fast mode */
#define I2C_Speed 400000 
/* Communication baud rate */
I2C_InitStructure.I2C_ClockSpeed = I2C_Speed;

Software simulation: No baud rate setting, how to calculate?

Through I2C bus bit delay function i2c_Delay:

static void i2c_Delay(void)
  uint8_t i;
  The following time is tested by Anfu Rui AX-Pro logic analyzer.
  CPU main frequency 72MHz, running in internal Flash, MDK project not optimized
  Loop count 10, SCL frequency = 205KHz
  Loop count 7, SCL frequency = 347KHz, SCL high time 1.5us, SCL low time 2.87us
  Loop count 5, SCL frequency = 421KHz, SCL high time 1.25us, SCL low time 2.375us
  IAR compilation efficiency is high, cannot be set to 7
  for (i = 0; i < 10; i++);

Application scenarios: PMIC, accelerometer, gyroscope.

6. SPI

Q1: How many lines does SPI need?

SPI interface usually uses 4 lines for communication:

MISO Master data input, slave data output.

MOSI Master data output, slave data input.

SCLK Clock signal, generated by master.

CS Slave chip select signal, controlled by master.

Q2: Four working modes of SPI?

SPI has four working modes, the difference is in different SCLK, specifically controlled by CPOL, CPHA.

(1) CPOL: (Clock Polarity), clock polarity.

SPI CPOL indicates the level when SCLK is idle, low level 0 or high level 1.

CPOL=0, clock is low when idle, so SCLK is high when active, called active-high;

CPOL=1, clock is high when idle, so SCLK is low when active, called active-low;

(2) CPHA: (Clock Phase), clock phase.

Phase corresponds to which edge (edge) for data sampling, first edge or second edge, 0 for first edge, 1 for second edge.

CPHA=0, first edge:

For CPOL=0, idle is low level, first edge is low to high, so rising edge;

For CPOL=1, idle is high level, first edge is high to low, so falling edge;

CPHA=1, second edge:

For CPOL=0, idle is low level, second edge is high to low, so falling edge;

For CPOL=1, idle is high level, first edge is low to high, so rising edge;

Q3: How to determine which mode to use?

(1) First confirm the required SCLK polarity of the slave, low or high when idle, to determine CPOL 0 or 1. Check schematic, we set idle state of serial sync clock to high, so we choose SPI_CPOL_High. That is CPOL=1.

(2) Then confirm from slave chip datasheet if data is sampled on SCLK falling edge or rising edge.

In summary: W25Q32JV is accessed via SPI compatible bus, including four signals: Serial Clock (CLK), Chip Select (/CS), Serial Data Input (DI) and Serial Data Output (DO).

Standard SPI instructions serially write commands, addresses or data into the device on CLK rising edges. DO output pin is used to read data or status from the device on CLK falling edges. It supports SPI bus operations of mode 0 (0,0) and mode 3 (1,1).

Mode 0 and mode 3 focus on the normal state of the CLK signal when the SPI bus master is idle and no data is being transferred to the serial Flash. For mode 0, CLK is normally low at the falling and rising edges of /CS. For mode 3, CLK is normally high on the falling and rising edges of /CS.

Since the idle state of the serial sync clock is high, we choose the second transition edge here, so select SPI_CPHA_2Edge. That is CPHA=1.

So we choose mode 3 (1,1).

Application scenarios: SPI Flash, W25Q32 memory capacity 32Mb (4M x 8), i.e. 4M bytes.

7. CAN

Q1: Summary introduction of CAN

CAN controller determines bus level based on voltage difference between CAN_L and CAN_H. Bus level is divided into dominant and recessive level. Sender sends message to receiver by changing bus level.

Q2: CAN initialization configuration steps?

(1) Configure related pin alternate function, enable CAN clock.

(2) Set CAN working mode and baud rate etc. (CAN initialization loopback mode, 500Kbps baud rate).

(3) Set filter.

Q3: CAN data sending format

CanTxMsg TxMessage;TxMessage.StdId=0x12; // Standard identifier
TxMessage.ExtId=0x12; // Set extended identifier
TxMessage.IDE=CAN_Id_Standard; // Standard frame
TxMessage.RTR=CAN_RTR_Data; // Data frame
TxMessage.DLC=len; // Length of data to send, send 8 bytes
  TxMessage.Data[i]=msg[i]; //Data

8. DMA

Q1: Introduction of DMA?

Direct Memory Access (DMA) is used to provide high-speed data transfer between peripherals and memory, or between memory and memory. Data can be quickly moved via DMA without CPU intervention, saving CPU resources for other operations.

Q2: How many transfer modes does DMA have?

DMA_Mode_Circular Circular mode

DMA_Mode_Normal Normal cache mode

Application scenarios: GPS, Bluetooth, use circular collection, DMA_Mode_Circular mode.

An important function is to get the remaining data size, subtract current remaining data from configured receive buffer size, to get current received data size.

9. Interrupt

Q1: Describe the interrupt handling process?

(1) Initialize interrupt, set trigger mode to rising edge/falling edge/both edges.

(2) Trigger interrupt, enter interrupt service routine.

Q2: How many external interrupts does STM32 interrupt controller support?

STM32 interrupt controller supports 19 external interrupt/event requests:

From the diagram, GPIO pins GPIOx.0~GPIOx.15(x=A,B,C,D,E,F,G) correspond to interrupt lines 0~15 respectively.

The other four EXTI lines are connected as follows:

● EXTI line 16 connects to PVD output

● EXTI line 17 connects to RTC alarm event  

● EXTI line 18 connects to USB wakeup event

● EXTI line 19 connects to Ethernet wakeup event (for connectivity products only)

Interrupt service routine list:

IO external interrupts are allocated only 7 interrupt vectors in vector table, so only 7 interrupt service routines can be used.








10. How many clock sources does STM32 have?

STM32 has 5 clock sources: HSI, HSE, LSI, LSE, PLL.

1. HSI is a high-speed internal RC oscillator clock with frequency 8MHz and low precision.

2. HSE is a high-speed external clock that can connect to a crystal/ceramic resonator, or external clock source, with frequency range 4MHz~16MHz.

3. LSI is a low-speed internal RC oscillator clock, with frequency 40kHz, providing low power clock.

4. LSE is a low-speed external clock, connecting to 32.768kHz crystal.

5. PLL is a phase-locked loop frequency multiplier output, clock input can be HSI/2, HSE or HSE/2. Multiplier can be 2~16, but output frequency cannot exceed 72MHz.

11. How are RTOS tasks written? How to switch out the task?

UCOS has a task scheduling mechanism for scheduling based on task priority.

One is hardware interrupt, the system will stack current task related variables, execute interrupt service routine, then unstack to return.

The other is task switching, using task scheduling method. Each task has its own stack, stacking on switch, executing another program, then unstacking to return.

Not each task executes in priority order in turns, but high priority task exclusively runs unless it voluntarily gives up execution, so low priority task cannot preempt. Meanwhile high priority can preempt CPU usage right given to low priority task. So need to insert wait delay in UCOS tasks to let low priority task execute when switched out.

12. What communication methods between tasks in UCOSII?

Use semaphores, mailboxes and message queues, these intermediates called events, and global variables, for inter-task communication in UCOSII.

Semaphores used for:

1. Control shared resource usage rights (meet mutual exclusion condition)

2. Indicate occurrence of a certain event

3. Synchronize behaviors of two tasks

Application example: Mutex semaphore

Initialized to 1 as mutual exclusion condition.

Goal: Call serial send command, must wait for return of “OK” character before sending next command. Each task may use this send function, cannot conflict!

Message queue:


(1) Message queue is actually mailbox array

(2) Tasks and interrupts can put a message into queue, tasks can get message from queue.

(3) Message entering queue first is given to task first (FIFO).

(4) Each message queue has a waiting list of tasks waiting for message. If no message in queue, waiting tasks are suspended until message arrives.

Application scenarios:

Serial receive program receive buffer.

Store external events.

13. Custom protocol is used in project, what is the structure?

Structure is: header (SDTC) + frame length + command + sequence number + data + CRC check.

14. Differences between uCOSII and Linux?

uC/OS-II is designed specifically for embedded applications of computers, with features like high execution efficiency, small space occupation, excellent real-time performance and strong scalability. Minimum kernel can be compiled to 2KB. uC/OS-II has been ported to almost all well-known CPUs.  

Linux is free, secure, stable, wide application range. It has extensive applications in embedded, server, home computers.

Both uC/OS-II and Linux are suitable for embedded use. But uC/OS-II is designed specifically for embedded, thus has higher running efficiency and less resource occupation.

Linux can also be used as server, with high usage rate. Although Linux is not developed specifically for server, its open source code allows full modification to minimize the difference, the most important distribution Red Hat Linux is widely used in servers.

15. Git code submission process?

1. Show modified files in current working path:

$ git status

2. Enter modified file directory:

$cd -

3. Show difference from last commit version file:

$ git diff

4. Add all current modifications to next commit:

$ git add .

5. Add related function description (use this for first commit):

$ git commit -s

Also note:

Fuction: modified code function

Ticket: corresponding Bug number

Note: redo above steps in each folder.

6. View submitted code

$ tig .

7. Do not modify published commit record! (use this for subsequent commits)

$git commit --amend

In command mode: 😡 (save file and exit)

8. Push to server

$ git push origin HEAD:refs/for/master

16. Comparison of ucosii, ucosiii and freeRTOS

Q1: Comparison of three?

ucosii and freeRTOS comparison:

(1) freeRTOS only supports TCP/IP, while uCOSii has extensive extensions like FS, USB, GUI, CAN support. (We use CAN for tbox, so choose uCOSii)

(2) freeRTOS is commercially free to use. uCOSii commercial use needs payment.

(3) Task communication in freeRTOS only supports queue, semaphore, mutex. uCOSii also supports event flags, mailbox in addition.

(4) In theory, freeRTOS can manage over 64 tasks, while uCOSii only 64.

ucosii and ucosiii comparison:

So what’s different from μC/OS-II to μC/OS-III? What has been added, we see that the changes are still significant.

One is that there were only 0~63 priority levels, and the priority levels can’t be duplicated, now several tasks are allowed to use the same priority level, and inside the same priority level, the time slice scheduling method is supported;

The second is to allow users to dynamically configure the real-time operating system kernel resources in the program run, for example, tasks, task stacks, signal volumes, event flag groups, message queues, message counts, mutually exclusive signal volumes, storage block divisions, and timers, which can be changed in the program run. In this way, users can avoid the problem of insufficient resource allocation during program compilation.

Some improvements have also been made in resource reuse. μC/OS-II has a maximum number of 64 tasks, and after version 2.82, it is 256. μC/OS-III allows the user to allocate by any number of tasks, any number of semaphores, mutex-type semaphores, event flags, message lists, timers, and any amount of storage block capacity, which is only limited by the amount of amount of RAM. This one is also a great extension.

17. Will ESP32 replace STM32 in the future?

  • 💡 ESP32 and STM32 have different strengths and weaknesses, suitable for different applications
  • 🤔 Many factors to consider when selecting a microcontroller for a product
  • 🔧 STM32 has better development tools, broader compatibility, more peripherals
  • 📶 ESP32 is great for WiFi/BT IoT devices, and STM32 is better for industrial apps
  • 📈 STM32 is seen as more reliable and stable for mission-critical uses
  • ⚙️ STM32 supports more interfaces like USB, Ethernet, CAN
  • 🧠 STM32 has better DSP capabilities for signal-processing apps
  • ⏱ STM32 has more timers/counters for precision timing tasks
  • 🤝 Not direct competition – both are excellent MCUs for different needs
  • Read More Details

Leave a Comment

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

Scroll to Top