当前位置:网站首页>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 .
边栏推荐
- QT charts use (rewrite qchartview to realize some custom functions)
- H3C VXLAN配置
- MySQL主从延迟的解决方案
- Greenplum6.x搭建_安装
- NCS Chengdu Xindian interview experience
- oracle一次性说清楚,多种分隔符的一个字段拆分多行,再多行多列多种分隔符拆多行,最终处理超亿亿。。亿级别数据量
- ncs成都新電面試經驗
- selenium自动化集成,八年测试经验软测工程师,一篇文章带你学懂
- 徽商期货公司评级是多少?开户安全吗?我想开户,可以吗?
- Enterprise manager cannot connect to the database instance
猜你喜欢
Goldbach conjecture C language
Pointer advanced, string function
MySQL主从延迟的解决方案
数字三角形模型 AcWing 1027. 方格取数
PPT模板、素材下载网站(纯干货,建议收藏)
Led analog and digital dimming
硬核分享:硬件工程师常用工具包
Reflections on the way of enterprise IT architecture transformation (Alibaba's China Taiwan strategic thought and architecture practice)
Synchronized underlying principle, volatile keyword analysis
2022-06-30 Unity核心8——模型导入
随机推荐
Esp32-ulp coprocessor low power mode RTC GPIO interrupt wake up
Simulation volume leetcode [general] 1557 The minimum number of points that can reach all points
Required String parameter ‘XXX‘ is not present
Analysis of abnormal channel number information before and after AGC re signature service
测试人一定要会的技能:selenium的三种等待方式解读,清晰明了
On December 8th, 2020, the memory of marketing MRC application suddenly increased, resulting in system oom
selenium自动化集成,八年测试经验软测工程师,一篇文章带你学懂
【ChaosBlade:节点 CPU 负载、节点网络延迟、节点网络丢包、节点域名访问异常】
Gson converts the entity class to JSON times declare multiple JSON fields named
Interpretation of MySQL optimization principle
[Yugong series] February 2022 U3D full stack class 008 - build a galaxy scene
Speaking of a software entrepreneurship project, is there anyone willing to invest?
数字三角形模型 AcWing 1027. 方格取数
Problems encountered in the use of go micro
leetcode135. Distribute candy
Un salaire annuel de 50 W Ali P8 vous montrera comment passer du test
The longest ascending subsequence model acwing 1017 Strange thief Kidd's glider
Find the original code, inverse code and complement of signed numbers [C language]
外部中断实现按键实验
Ppt template and material download website (pure dry goods, recommended Collection)