当前位置:网站首页>STM32 how to use serial port
STM32 how to use serial port
2022-07-26 22:38:00 【*Black heart radish three bars*】
One 、 Relevant knowledge reserve
1、 Serial communication and parallel peer
- serial communication : Serial communication is to use only one data line to transmit data in data communication , Transmit data bit by bit ;
- Parallel communication : Parallel communication means using multiple data lines to transmit data , Multiple data can also be transmitted at one time , Generally, it is transmitted in the form of words or bytes ;
difference : Data communication is like a car driving on the road , Serial communication is that there is only one single lane on this road , At the same time, vehicles traveling in the same direction can only pass one by one ; And parallel communication , Parallel communication means that there are multiple lanes on this road , Multiple cars can be driven in the same direction at the same time .
2、 Synchronous communication and asynchronous communication
- Asynchronous communication data transmission is transmitted by frame , A frame of data contains the start bit 、 Data bits 、 Check bit and stop bit .
- Synchronous communication is made by 1~2 Synchronous characters and multi byte data bits , The synchronization character is used as the starting bit to trigger the synchronization clock to start sending or receiving data ; No gap is allowed between multi byte data , Each person takes up the same amount of time ; The idle bit needs to send synchronization characters .
3、 The mechanism of serial communication
- Simplex (Simplex) It means that both parties can only transmit data in one direction when communicating . After the system is composed , The sender and receiver are fixed .
- Half duplex (Half Duplex) It means that both sides of communication have transmitters and receivers , You can send or receive , But it cannot receive and send at the same time , Cannot receive when sending , Cannot send when receiving .
- Full duplex system (Full Duplex) It means that both sides of the communication are equipped with transmitters and receivers , And the channel is divided into sending channel and receiving channel , Therefore, the full duplex system can realize two-way simultaneous sending and receiving data , Can receive when sending , It can also be sent when receiving
4、 data verification
- Parity check
Parity when sending data , Data bits follow 1 The bits of are parity bits (1 or 0), When set to odd check , In the data 1 Number of and check bits 1 The sum of the number of should be odd ; When set to even check , In the data 1 The number of and in the check digit 1 The sum of the number of should be an even number . - Add up and check
Cumulative sum check refers to the sender summing the sent data blocks , And will “ The checksum ” Append to end of data block . When receiving data, the receiver also sums the data blocks , Compare the result with the sender's “ The checksum ” Compare , If it is consistent, there is no error , Otherwise, there will be a mistake . - Cyclic redundancy check
The basic principle of cyclic redundancy code check is to treat a data block as a binary number with a long number of digits , Then divide it by a specific number , The remainder is attached to the data block as a check code and sent together .
5、 Baud rate
Baud rate is the rate of analog line signal , Also known as modulation rate , Measured by the number of oscillations per second of the waveform . Wave refers to the modulation rate of the data signal to the carrier , It is expressed by the number of carrier modulation state changes per unit time , Its unit is baud (Baud). The relationship between baud rate and bit rate is bit rate = Baud rate X The number of bits corresponding to a single modulation state . In the information transmission channel , The signal unit carrying data information is called symbol , The number of symbols transmitted through the channel per second is called the symbol transmission rate , Baud rate for short . Baud rate is the index of transmission channel bandwidth . The amount of information transmitted through the channel per second is called bit transmission rate , Bit rate for short . The bit rate represents the transmission rate of effective data .
- 1 potter =1 position / second (1bit/s)
6、 The mechanism of serial communication
- Simplex communication : Simplex communication means that after the communication mechanism is established , Fix the receiver and sender , Both cannot be changed , The receiver can only receive , The sender can only send ;
- Half duplex communication : Half duplex communication means that after the communication mechanism is established , The receiver and the sender can be interchanged , But the same port cannot be the sender , As the receiver ;
- Full duplex communication : Full duplex communication means that after the communication mechanism is established , The receiver can also act as the sender , Again , The sender can also act as the receiver ;
Two 、 A serial port (USART)
1、 Introduction of serial port
A serial port (USART), Also known as universal synchronous asynchronous transceiver (Universal Synchronous/Asynchronous Receiver/Transmitter USART), It provides a flexible approach with the use of industry standards NRZ Full duplex data exchange between external devices in asynchronous serial data format . USART Using fractional baud rate generator to provide a wide range of baud rate selection . It supports synchronous one-way communication and half duplex single line communication , Also support LIN( Local Internet ), Smart card protocol and IrDA( Infrared data organization )SIR ENDEC standard , And modem (CTS/RTS) operation . It also allows multiprocessor communication . Using a multi buffer configuration DMA The way , It can realize high-speed data communication .
2、 Function introduction
(1)、USART_InitTypeDefstructure Structure introduction
USART_InitTypeDefstructure Defined in "stm32f10x_usart.h" In file , The member variables of the structure are as follows :

USART_InitTypeDefstructure member USART Pattern contrast

USART_InitTypeDefstructure Member variables USART_BaudRate The definition of
This member is set USART Baud rate of transmission , Baud rate can be calculated by the following formula :
IntegerDivider =((APBClock)/ (16*(USART_InitStruct->USART_BaudRate)))FractionalDivider = ((IntegerDivider - ((u32)IntegerDivider))*16)+0.5USART_InitTypeDefstructure Member variables USART_WordLenth The definition of
USART_WordLenth Defines the number of bits of data transmission in a frame , It has two values USART_WordLeth_8b( Eight digit data ) And USART_WordLeth_9b( Nine digit data ).USART_InitTypeDefstructure Member variables USART_StopBits The definition of
USART_StopBits Is a variable used to set the stop bit of transmission at the end of the frame , The following table is a detailed description of the variable value :
USART_InitTypeDefstructure Member variables USART_Parity The definition of

( Be careful : Once parity is enabled , Sending data MSB Bit inserts the computed parity bit ( The word is 9 The first of bit 9 position , The word is 8 The first of bit 8 position ).)USART_InitTypeDefstructure Member variables USART_HardwareFlowControl The definition of
USART_HardwareFlowControl Specifies whether the hardware flow control mode is enabled or disabled . Please see the table below for the specific mode :
USART_InitTypeDefstructure Member variables USART_Mode Definition
USART_Mode Set the enable or disable sending and receiving mode of the serial port , The following table shows the detailed mode selection :
USART_InitTypeDefstructure Member variables USART_CLOCK Definition
USART_CLOCK Set up USART Is the clock enabled or disabled , The following is a detailed description of the options of this variable :
USART_InitTypeDefstructure Member variables USART_CPOL The definition of
USART_CPOL Specify the following SLCK Polarity of clock output on pin . The following table is a detailed description of the variable value :
USART_InitTypeDefstructure Member variables USART_APHA The definition of
USART_CPHA Specify the following SLCK The phase of the clock output on the pin , and CPOL Bits work together to produce the user's desired clock / Sampling relationship of data . The detailed description of its value is shown in the figure below :

- USART_InitTypeDefstructure Member variables USART_LastBit The definition of
USART_LastBit To control whether it is in synchronous mode , stay SCLK The last data word sent is output on the pin (MSB) Corresponding clock pulse . The following figure shows the optional values and descriptions of parameters :
(2)、 Interrupt register USART_Init function

(3)、 Interrupt data transmission USART_SendData function

(4)、 Interrupt data reception USART_ReceiveData function

(5)、 Check the specified interrupt flag bit function USART_GetFlagStatus function

2、 Example
utilize STM32 The development board receives PC Data sent by the end , Displayed on the nixie tube , And send the cumulative total number of received data to PC End .
(1)、 Global variables
// Save serial port 1 Data received
unsigned char uart1_date[6];
// Define the amount of data received
u8 uart1_date_number = 0;
// Save serial port 1 Data received
unsigned char d1,d2,d3;
(2)、 The main function
extern unsigned char d1,d2,d3;
int main(void)
{
u8 old_number = uart1_date_number;
time6_init();
seg_GPIO_Init();
uart1_init();
while(1){
segbuff[0] = d1/16;
segbuff[1] = d1%16;
segbuff[2] = d2/16;
segbuff[3] = d2%16;
segbuff[4] = d3/16;
segbuff[5] = d3%16;
// Determine whether data is received , Send the data after receiving the data
if(old_number != uart1_date_number){
sendData(uart1_date_number);
old_number = uart1_date_number;
}
}
}
(3)、 Interrupt initialization function
/* * @ The functionality : A serial port 1 The initialization * @ Parameters nothing * @ Return value nothing */
void uart1_init(void)
{
/* Define initialization variables */
GPIO_InitTypeDef GPIO_InitStructrue;//GPIO initialization
USART_InitTypeDef USART_InitStructrue;// A serial port uart1 initialization
NVIC_InitTypeDef NVIC_InitStructrue;//NVIC initialization
/* Turn on timer */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_USART1|RCC_APB2Periph_AFIO,ENABLE);
/* To configure GPIO Patterns and IO mouth be used for GPIO initialization */
GPIO_InitStructrue.GPIO_Pin = GPIO_Pin_9;// choice GPIO The pin of UART1 The output related pin is Pin9
GPIO_InitStructrue.GPIO_Speed = GPIO_Speed_50MHz;// Set up GPIO The frequency of
GPIO_InitStructrue.GPIO_Mode = GPIO_Mode_AF_PP;// Set up GPIO The mode is multiplex push-pull output mode
GPIO_Init(GPIOA,&GPIO_InitStructrue);
GPIO_InitStructrue.GPIO_Pin = GPIO_Pin_10;// choice GPIO The pin of UART1 The output related pin is Pin9
GPIO_InitStructrue.GPIO_Speed = GPIO_Speed_50MHz;// Set up GPIO The frequency of
GPIO_InitStructrue.GPIO_Mode = GPIO_Mode_IN_FLOATING;// Set up GPIO The mode is analog input mode
GPIO_Init(GPIOA,&GPIO_InitStructrue);
/* Serial initialization */
USART_InitStructrue.USART_BaudRate = 9600;// Set the baud rate of the serial port
USART_InitStructrue.USART_WordLength = USART_WordLength_8b;// Set the data length to 8 position
USART_InitStructrue.USART_StopBits = USART_StopBits_1;// The setting data has 1 Stop bit of bit
USART_InitStructrue.USART_Parity = USART_Parity_No;// Serial port data has no check bit
USART_InitStructrue.USART_HardwareFlowControl = USART_HardwareFlowControl_None;// Set the serial port to disable hardware flow
USART_InitStructrue.USART_Mode = USART_Mode_Tx|USART_Mode_Rx;// Turn on the sending and receiving mode of the serial port
USART_Init(USART1,&USART_InitStructrue);// initialization USART1
USART_Cmd(USART1,ENABLE);// Enable serial port 1
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);// Can make USART1 interrupt
USART_ClearFlag(USART1,USART_FLAG_TC);// eliminate USARTx Pending flag bit
/* Set up NVIC Parameters of */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);// Set up NVIC The grouping
NVIC_InitStructrue.NVIC_IRQChannel = USART1_IRQn;// Appoint NVIC Passageway is USART1 passageway
NVIC_InitStructrue.NVIC_IRQChannelPreemptionPriority = 0;// Set interrupt preemption priority
NVIC_InitStructrue.NVIC_IRQChannelSubPriority = 0;// Set interrupt response priority
NVIC_InitStructrue.NVIC_IRQChannelCmd = ENABLE;// Set interrupt nesting to enable
NVIC_Init(&NVIC_InitStructrue);//NVIC initialization
}
(4)、 Interrupt service function
/* * @ The functionality : A serial port 1 The interrupt service function of * @ Parameters nothing * @ Return value nothing */
void USART1_IRQHandler(void)
{
USART_ClearFlag(USART1,USART_FLAG_TC); // Clear the flag bit of interrupt transmission completion Indicates that sending data has been completed
if(uart1_date_number == 0){
d1 = USART_ReceiveData(USART1);
}else if(uart1_date_number == 1){
d2 = USART_ReceiveData(USART1);
}else{
d3 = USART_ReceiveData(USART1);
}
uart1_date_number++;
uart1_date_number = uart1_date_number%3;
}
(5)、 Data sending function
/* * The functionality Send serial data * Parameters u8 data: Data sent * Return value nothing */
void sendData(u8 data)
{
USART_SendData(USART1,uart1_date_number);// Peripherals through USARTx Send single data
// Check whether the null flag bit of the transmit data register is reset If it is empty, it means that data can be stored inside
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==Bit_RESET)
;
}
3、 ... and 、 Problems encountered
In the above code, we need to pay attention to : Receiving PC It's better not to use an array to receive data when sending data from the client .( Xiaobian has tried , However, the data sent does not correspond to the data of the array ) The methods of receiving data and displaying data are attached below :
- Method of receiving data :
uart1_date[uart1_date_number]=USART_ReceiveData(USART1);// Accept serial port 1 The data of
- Method of displaying data :
// Try 1
segbuff[0] = uart1_date[1];
segbuff[1] = uart1_date[0];
segbuff[2] = uart1_date[3];
segbuff[3] = uart1_date[2];
segbuff[4] = uart1_date[5];
segbuff[5] = uart1_date[4];
// Try 2
segbuff[0] = uart1_date[0]/16;
segbuff[1] = uart1_date[0]%16;
segbuff[2] = uart1_date[1]/16;
segbuff[3] = uart1_date[1]%16;
segbuff[4] = uart1_date[2]/16;
segbuff[5] = uart1_date[2]%16;
Four 、 attach
- When sending data , You can not put the function that sends data in the main function , It can also be placed when the serial port receives data , To do so , We don't have to judge whether the data is received , It can be sent every time the serial port interrupt function is triggered .
- You can go to other related functions STM32- Refresh the nixie tube
边栏推荐
- 基于gRPC编写golang简单C2远控
- Let the program do one thing in one or more seconds
- Summary of shell related commands
- 国产DRAM年底将量产,但前路依旧漫漫!
- what is a kit in qt
- Do you know why to design test cases after learning so long about use case design
- Nacos作为注册中心、配置中心入门使用篇-实现远程调用、动态获取配置文件、数据库配置信息
- 动态规划之线性DP
- Matlab solution of the densest stacking and smallest circumscribed square of N circles (two-dimensional, three-dimensional, etc. circle packing problem)
- Sell 700million a year, and get ready for the IPO of Dezhou braised chicken
猜你喜欢

Embedded sig | distributed soft bus

Internet celebrity spicy bars can't catch young people

【论文阅读】LOGAN:Membership Inference Attacks Against Generative Models

基于C语言的页式文件系统

Introduction to MySQL database
![[MySQL] - index principle and use](/img/e1/af74ee20ebe0c6e6f5e453330cc13b.png)
[MySQL] - index principle and use

IDEA的那些环境配置及插件

JSON字符串转化为JSON对象,获取某个key的值,判断某个key是否存在

Cached database for memcached

yolov1
随机推荐
【论文阅读】LOGAN:Membership Inference Attacks Against Generative Models
Embedded sig | distributed soft bus
三星Galaxy Z可折叠产品的预告片泄露:'柔性好于平面'
[MySQL] - index principle and use
Introduction to MySQL database
芯鼎收购紫光控股!万业企业:全面转型集成电路!
Financial institution map
y78.第四章 Prometheus大厂监控体系及实战 -- prometheus的服务发现机制(九)
Summary of shell related commands
Leetcode:857. Minimum cost of employing K workers [think in blocks + start with simplicity]
Matlab solution of the densest stacking and smallest circumscribed square of N circles (two-dimensional, three-dimensional, etc. circle packing problem)
View drawing process 1-the relationship between view and window
Makefile相关语法总结(Openc910)
Does Guosen Securities charge for opening a mobile account? Is it safe to open an account?
08.02 adjacency table
Luo Xu talks with Siemens wanghaibin: advanced manufacturing requires benefits from Digitalization
what crlf mean
Module 8 (message queue MySQL table storing message data)
继关闭苏州厂之后,欧姆龙东莞厂宣布解散,2000多人面临失业!
商汤科技CEO徐立:公司估值已超70亿美元,不急于上市