How to set up the serial port program in STM32 microcontroller

The following takes the STM32F103C8T6 microcontroller as an example to introduce how to set up the serial port program in the STM32 microcontroller.

Serial port hardware connection
In the STM32F103C8T6 microcontroller, there are multiple USART modules available. The pinout of these USART modules is as follows:

USART1: PA9 (Tx), PA10 (Rx)
USART2: PA2 (Tx), PA3 (Rx)
USART3: PB10 (Tx), PB11 (Rx)
When using one of the USART modules, you need to connect its Tx pin to The Rx pin of the external device, connect its Rx pin to the Tx pin of the external device.

Settings of serial port registers
In the STM32 microcontroller, the serial port registers include USART_SR, USART_DR, USART_BRR, USART_CR1, USART_CR2 and USART_CR3, etc. The functions of these registers are as follows:

USART_SR: Serial port status register, including transmission completion flag bit TC, data register empty flag bit TXE and receive register non-empty flag bit RXNE, etc.
USART_DR: Serial port data register, used to store data to be sent or received.
USART_BRR: Serial port baud rate register, used to set the baud rate.
USART_CR1: Serial port control register 1, including serial port enable bit UE, transmit enable bit TE, receive enable bit RE and idle interrupt enable bit IDLEIE, etc.
USART_CR2: Serial port control register 2, used to set data length, stop number, check bit, etc.
USART_CR3: Serial port control register 3, used to set hardware flow control, etc.
In the STM32 microcontroller, the steps to set up the serial port program are as follows:

1) Enable USART clock

The clock of the USART module needs to be enabled in the RCC_APB2PeriphClockCmd() function.

2) Set GPIO pin mode

Set the USART's Tx and Rx pins as alternate functions, which can be set using the GPIO_Init() function.

3) Set the baud rate

Set the USART_BRR register to the desired baud rate, which can be set using the USART_Init() function.

4) Enable serial port

By setting the UE, TE and RE bits of the USART_CR1 register, the sending and receiving functions of the serial port are enabled, which can be set using the USART_Cmd() function.

5) Send data

The data is sent by writing the data that needs to be sent into the USART_DR register.

The following is the code implementation of a simple STM32 serial port sending program:
Insert image description here

Guess you like

Origin blog.csdn.net/der_power/article/details/129390588