当前位置:网站首页>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 .
边栏推荐
- Greenplum6.x常用语句
- Skills that testers must know: Selenium's three waiting ways are interpreted clearly
- 年薪50w阿裏P8親自下場,教你如何從測試進階
- Calculation s=1+12+123+1234+12345 C language
- go mod module declares its path as: gtihub. com/xxx-xx but was required as:xx-xx
- Synchronized underlying principle, volatile keyword analysis
- Redis fault handling "can't save in background: fork: cannot allocate memory“
- Original collection of hardware bear (updated on June 2022)
- 【ChaosBlade:根据标签删除POD、Pod 域名访问异常场景、Pod 文件系统 I/O 故障场景】
- Explain Huawei's application market in detail, and gradually reduce 32-bit package applications and strategies in 2022
猜你喜欢

2022-06-30 unity core 8 - model import
![[Yugong series] February 2022 U3D full stack class 007 - production and setting skybox resources](/img/e3/3703bdace2d0ca47c1a585562dc15e.jpg)
[Yugong series] February 2022 U3D full stack class 007 - production and setting skybox resources

Lenovo hybrid cloud Lenovo xcloud: 4 major product lines +it service portal

Digital triangle model acwing 275 Pass a note

LeetCode 715. Range module

ncs成都新電面試經驗

xray的简单使用

leetcode134. gas station

Reflections on the way of enterprise IT architecture transformation (Alibaba's China Taiwan strategic thought and architecture practice)

C language for calculating the product of two matrices
随机推荐
Port occupation troubleshooting
systemd
Digital triangle model acwing 1027 Grid access
Greenplum 6.x build_ install
On December 8th, 2020, the memory of marketing MRC application suddenly increased, resulting in system oom
Greenplum 6.x version change record common manual
2022-07-06 unity core 9 - 3D animation
2022-06-30 unity core 8 - model import
Greenplum6.x搭建_安装
Goldbach conjecture C language
模拟卷Leetcode【普通】1705. 吃苹果的最大数目
go mod module declares its path as: gtihub. com/xxx-xx but was required as:xx-xx
Greenplum6.x常用语句
Explain Huawei's application market in detail, and gradually reduce 32-bit package applications and strategies in 2022
Unity Shader入门精要初级篇(一)-- 基础光照笔记
Output all composite numbers between 6 and 1000
Database storage - table partition
Markdown编辑器Editor.md插件的使用
Simulation volume leetcode [general] 1567 Length of the longest subarray whose product is a positive number
C language for calculating the product of two matrices
