当前位置:网站首页>Serial port experiment - simple data sending and receiving
Serial port experiment - simple data sending and receiving
2022-07-07 08:58:00 【A big cat 1201】
author : A big cat 1201
special column :《STM32 Study 》
Maxim : You just try to , Leave the rest to time !
Serial port experiment
describe
Serial port as MCU Important external interfaces , At the same time, it is also an important debugging means of software development , Its importance is self-evident . Now basically everything MCU Will have a serial port ,STM32 Nature is no exception .
STM32 Serial port resources are quite rich , It's also quite powerful . Used by benmew STM32F103ZET6 At most 5 Serial port , There's a fractional baud rate generator 、 Support synchronous single line communication and half duplex single line communication 、 Support LIN、 Support modem operation 、 Smart card protocol and IrDA SIR ENDEC standard 、 have DMA etc. .
Receive status flag
#define USART_REC_LEN 200 // Define the maximum number of bytes received 200
#define EN_USART1_RX 1 // Can make (1)/ prohibit (0) A serial port 1 receive
extern u8 USART_RX_BUF[USART_REC_LEN]; // Receive buffer , Maximum USART_REC_LEN Bytes . The last byte is a newline character
extern u16 USART_RX_STA; // Receive status flag
In the official library function usart.h The maximum number of bytes received is defined in , yes 200 Bytes , And create an array , The size of the array is 200 Bytes , Each byte of data received is put into this array .
And a variable is used USART_RX_STA, This is a variable of individual receiving status , Its size is 16 A bit , That is, two bytes .
This is the meaning of each of its representatives .
- 0 To 13 Bits store the number of valid data received , Every time you receive a valid data , Will add 1.
- The first 14 Whether representatives accept 0X0D data , That is, the carriage return character . We stipulate for this serial communication , So enter (0X0D) Line break (0X0A) Character end communication . If the received data is 0X0D The position will be 1.
- The first 15 Whether the representatives have finished receiving . If the received data is 0X0D( Carriage return character ) The next data is 0X0A( Newline characters ), It indicates that the reception is completed , The position will be 1.
The above regulations are agreed by both parties before communication , Both sides of the communication should follow this agreement .
Function configuration
Our experiment only realizes simple data sending and receiving .5 In serial ports , We choose serial port 1(UASRT1) Realize this experiment .
In this meow's article Serial port register function configuration How to configure the serial port has been described in detail in , Here, benmew will directly configure , No more reason .
- Can make GPIOA and USART1 The clock of
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); // Can make USART1,GPIOA The clock
- To configure GPIOA mouth
GPIO_InitTypeDef GPIO_InitStructure;
//USART1_TX GPIOA.9
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // Multiplexing push pull output
GPIO_Init(GPIOA, &GPIO_InitStructure);// initialization GPIOA.9
//USART1_RX GPIOA.10 initialization
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;// Floating input
GPIO_Init(GPIOA, &GPIO_InitStructure);// initialization GPIOA.10
USART_Init(USART1, &USART_InitStructure); // Initialize serial port 1
- Configure serial port
USART_InitTypeDef USART_InitStructure;
//USART Initialize settings
USART_InitStructure.USART_BaudRate = bound;// Serial port baud rate
USART_InitStructure.USART_WordLength = USART_WordLength_8b;// The word is 8 Bit data format
USART_InitStructure.USART_StopBits = USART_StopBits_1;// A stop bit
USART_InitStructure.USART_Parity = USART_Parity_No;// No parity bit
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;// No hardware data flow control
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; // Transceiver mode
- Configure interrupt priority
NVIC_InitTypeDef NVIC_InitStructure;
//Usart1 NVIC To configure
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;// preemption 3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; // Sub priority 3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ Channel enable
NVIC_Init(&NVIC_InitStructure); // Initialize... According to the specified parameters VIC register
- Turn on receive interrupt
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);// Open serial port to accept interrupt
- Serial port enable
USART_Cmd(USART1, ENABLE); // Enable serial port 1
- Write interrupt service function
void USART1_IRQHandler(void) // A serial port 1 Interrupt service routine
{
u8 Res;
#if SYSTEM_SUPPORT_OS // If SYSTEM_SUPPORT_OS It's true , Support is needed OS.
OSIntEnter();
#endif
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) // Receive interrupt ( The data received must be 0x0d 0x0a ending )
{
Res =USART_ReceiveData(USART1); // Read received data
if((USART_RX_STA&0x8000)==0)// Reception is not complete
{
if(USART_RX_STA&0x4000)// received 0x0d
{
if(Res!=0x0a)USART_RX_STA=0;// Receive error , restart
else USART_RX_STA|=0x8000; // The reception is complete
}
else // I haven't received 0X0D
{
if(Res==0x0d)USART_RX_STA|=0x4000;
else
{
USART_RX_BUF[USART_RX_STA&0X3FFF]=Res ;
USART_RX_STA++;
if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0;// Receiving data error , Start receiving again
}
}
}
}
#if SYSTEM_SUPPORT_OS // If SYSTEM_SUPPORT_OS It's true , Support is needed OS.
OSIntExit();
#endif
}
- After entering the interrupt function, create a 1 A variable with a size of bytes Res, Used to store received data .
- It is necessary to judge whether the reception interrupt occurs , If the interrupt is received, continue to execute the interrupt service program , If it is another interrupt, the interrupt service program will not be executed .
- Judge whether the highest bit in the receive status flag is 1, If it is 1 It means that the data reception has been completed , No more receiving , If it is 0 It means that the data reception has not been completed , Need to continue receiving .
- Judgment No. 14 Whether a is 1, yes 1 Then the last data is 0X0D That is, the carriage return character , Then it is necessary to judge whether the next data is 0X0A That is, newline characters , If it's not a newline character , It means that this data is received incorrectly , Need to receive again , If it is a newline character, it means that the data reception is completed , You need to put the highest position 1.
- Judgment No. 14 Is it 0 When , It shows that the data is still receiving , When receiving a data, it is necessary to judge whether it is 0X0D That is, the carriage return character , And set the corresponding flag bit .
- When the previous data and this data are not 0X0D When , Put the received data in the array , The subscript of the array is 0 To 13 Number of valid data in bits .
The above function configuration process does not need to be written line by line , stay ST Official library functions usart.c There are these functions in , We can use it directly .
- Write main program
The code in the main program needs to be written by ourselves
#include "delay.h"
#include "usart.h"
#include "led.h"
int main(void)
{
u8 len = 0;// Number of stored data
u8 t = 0;// Loop control variable
LED_Init();//LED0 initialization
delay_init();// Delay initialization
uart_init(115200);// Serial initialization , The baud rate is 115200
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);// Priority grouping uses the second group
while(1)
{
// Send when data reception is complete
if(USART_RX_STA&0x8000)
{
len = USART_RX_STA&0x3fff;// Get the data length
printf("\r\n The data you sent is :\r\n");
// Send all data
for(t = 0; t < len; t ++)
{
USART_SendData(USART1,USART_RX_BUF[t]);// Send a data
while(USART_GetFlagStatus(USART1,USART_FLAG_TC) != SET)
{
;// Waiting until a data is sent
}
}
printf("\r\n\r\n");
USART_RX_STA = 0;// Clear the status after sending all the data 0
}
// Wait for data reception when data reception is not completed
else
{
printf("\r\n Please input data , Press enter to finish :\r\n");
while((USART_RX_STA&0x8000)==0)
{
LED0 = !LED0;
delay_ms(500);//led Light flashing , Waiting for data input
}
}
}
}
This is all the code of serial port experiment .
Effect display

On the serial port debugging assistant , After entering the content, click send , The receiving window will display the input .
When there is no input , On the development board LED The light is flashing , Don't take photos of the development board here .
summary
The experiment mainly lies in the compilation of the main program , Because other initialization functions are ST Official library functions , If we need to use other serial ports or have other requirements , Just modify the library function slightly .
边栏推荐
- Pointer advanced, string function
- With an annual salary of 50W, Alibaba P8 will come out in person to teach you how to advance from testing
- 模拟卷Leetcode【普通】1706. 球会落何处
- Alibaba P8 teaches you how to realize multithreading in automated testing? Hurry up and stop
- STM32串口寄存器库函数配置方法
- 【ChaosBlade:根据标签删除POD、Pod 域名访问异常场景、Pod 文件系统 I/O 故障场景】
- Introduction to data fragmentation
- How to realize sliding operation component in fast application
- Analysis of Hessian serialization principle
- ncs成都新电面试经验
猜你喜欢

The longest ascending subsequence model acwing 1017 Strange thief Kidd's glider

Image segmentation in opencv

leetcode134. gas station

Ppt template and material download website (pure dry goods, recommended Collection)

Greenplum6.x重新初始化

Troublesome problem of image resizing when using typora to edit markdown to upload CSDN

阿里p8推荐,测试覆盖率工具—Jacoco,实用性极佳

Digital triangle model acwing 1027 Grid access

【Istio Network CRD VirtualService、Envoyfilter】

Screen automatically generates database documents
随机推荐
Markdown编辑器Editor.md插件的使用
9c09730c0eea36d495c3ff6efe3708d8
Selenium automation integration, eight years of testing experience, soft test engineer, an article to teach you
平台化,强链补链的一个支点
Esp32-ulp coprocessor low power mode RTC GPIO interrupt wake up
NCS Chengdu New Electric interview Experience
ChaosBlade:混沌工程简介(一)
leetcode134. gas station
面试题:高速PCB一般布局、布线原则
Count the number of words C language
C language for calculating the product of two matrices
【ChaosBlade:节点磁盘填充、杀节点上指定进程、挂起节点上指定进程】
使用Typora编辑markdown上传CSDN时图片大小调整麻烦问题
OpenGL 3D graphics rendering
[wechat applet: cache operation]
2022-07-06 unity core 9 - 3D animation
Reflections on the way of enterprise IT architecture transformation (Alibaba's China Taiwan strategic thought and architecture practice)
How to realize sliding operation component in fast application
MySQL partition explanation and operation statement
Lenovo hybrid cloud Lenovo xcloud: 4 major product lines +it service portal
