当前位置:网站首页>[STM32 learning] (7) use of serial port 2 (usart2)
[STM32 learning] (7) use of serial port 2 (usart2)
2022-07-24 09:51:00 【Use small materials】
SCM serial port must be learned , And it's important , It is very important in data transmission and program debugging .
Learn more about this blog USART2 A serial port
In fact, not every serial port IO Can be used as serial port , He is fixed IO Oral .
Such as USART1 Serial port corresponding to IO yes PA9、PA10, This is very important , Don't get it wrong . The material document is shown in the figure below :

STM32 General steps of serial port configuration ( Library function )
(1) Serial clock enable :RCC_APBxPeriphClockCmd();
GPIO Clock enable :RCC_AHBxPeriphClockCmd();
(2) Pin multiplexing mapping :GPIO_PinAFConfig();
(3)GPIO Port mode configuration :GPIO_Init(); The mode is configured to GPIO_Mode_AF
(4) Initialization of serial port parameters :USART_Init();
(5) Turn on interrupt and initialize NVIC( If you need to turn on interrupt, you need this step )
NVIC_Init();
USART_ITConfig();
(6) Enable serial port :USART_Cmd();
(7) Write interrupt handling functions :USARTx_IRQHandler();
(8) Serial data transmission :
void USART_SendData();// Send data to serial port ,DR
uint16_t USART_ReceiveData();// receive data , from DR Read the received data
(9) Serial port transmission state acquisition :
FlagStatus USART_GetFlagStatus();
void USART_ClearITPendingBit();
The model of single chip microcomputer I use here is STM32F103VET
The code is as follows :
main.c
#include "led.h"
#include "delay.h"
#include "key.h"
#include "sys.h"
#include "usart.h"
int main(void)
{
u8 t;
u8 len;
u16 times=0;
delay_init(); // Delay function initialization
NVIC_Configuration(); // Set up NVIC Interrupt grouping 2:2 Bit preemption priority ,2 Bit response priority
uart2_init(9600); // The serial port is initialized to 9600
LED_Init(); //LED Port initialization
KEY_Init(); // Initialize the hardware interface connected with the key
while(1)
{
if(USART_RX_STA&0x8000)
{
len=USART_RX_STA&0x3fff;// The length of data received this time
printf(" The message you sent is :\r\n");
for(t=0;t<len;t++)
{
USART_SendData(USART2, USART_RX_BUF[t]);// Serial port 2 send data
while(USART_GetFlagStatus(USART2,USART_FLAG_TC)!=SET);// Wait for the end of sending
}
printf("\r\n");// Insert newline
USART_RX_STA=0;
}
else
{
times++;
if(times%5000==0)
{
printf("\r\n Serial port experiment \r\n");
printf("wantin\r\n\r\n");
}
if(times%200==0)printf(" Please input data , End with enter \n");
if(times%30==0)LED0=!LED0;// flashing LED, Indicates that the system is running .
delay_ms(10);
}
}
}
usart.h
#ifndef __USART_H
#define __USART_H
#include "stdio.h"
#include "sys.h"
//
//
#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
// If you want to interrupt the receiving serial port , Please do not comment on the following macro definition
void uart2_init(u32 bound);
#endif
usart.c
#include "sys.h"
#include "usart.h"
//
//
//
// Add the following code , Support printf function , You don't need to choose use MicroLIB
#if 1
#pragma import(__use_no_semihosting)
// Support functions required by the standard library
struct __FILE
{
int handle;
};
FILE __stdout;
// Definition _sys_exit() To avoid using semi host mode
void _sys_exit(int x)
{
x = x;
}
// redefinition fputc function
int fputc(int ch, FILE *f)
{
while(USART_GetFlagStatus(USART2,USART_FLAG_TC)==RESET);
USART_SendData(USART2,(uint8_t)ch);
return ch;
}
#endif
/* Use microLib Methods */
/*
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (uint8_t) ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {}
return ch;
}
int GetKey (void) {
while (!(USART1->SR & USART_FLAG_RXNE));
return ((int)(USART1->DR & 0x1FF));
}
*/
#if EN_USART1_RX // If enabled, receive
// A serial port 1 Interrupt service routine
// Be careful , Read USARTx->SR Can avoid inexplicable mistakes
u8 USART_RX_BUF[USART_REC_LEN]; // Receive buffer , Maximum USART_REC_LEN Bytes .
// Reception status
//bit15, Receive completion flag
//bit14, Received 0x0d
//bit13~0, Number of valid bytes received
u16 USART_RX_STA=0; // Receive status flag
void uart2_init(u32 bound){
//GPIO Port settings
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); // Can make USART2 The clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); // Can make GPIOA The clock
USART_DeInit(USART2); // Reset serial port 2
//USART2_TX PA.2
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //PA.2
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 PA2
//USART2_RX PA.3
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;// Floating input
GPIO_Init(GPIOA, &GPIO_InitStructure); // initialization PA3
//USART Initialize settings
USART_InitStructure.USART_BaudRate = bound;// Generally set as 9600;
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
USART_Init(USART2, &USART_InitStructure); // Initialize serial port
#if EN_USART1_RX // If enabled, receive
//Usart1 NVIC To configure
NVIC_InitStructure.NVIC_IRQChannel = USART2_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
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);// Open interrupt
#endif
USART_Cmd(USART2, ENABLE); // Enable serial port
}
void USART2_IRQHandler(void) // A serial port 2 Interrupt service routine
{
u8 Res;
#ifdef OS_TICKS_PER_SEC // If the number of clock beats is defined , Explain to use ucosII 了 .
OSIntEnter();
#endif
if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) // Receive interrupt ( The data received must be 0x0d 0x0a ending )
{
Res =USART_ReceiveData(USART2);//(USART1->DR); // 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
}
}
}
}
#ifdef OS_TICKS_PER_SEC // If the number of clock beats is defined , Explain to use ucosII 了 .
OSIntExit();
#endif
}
#endif
The rest USRT3-USART5 Are implemented in the same way , But here's the thing , But open multiple at the same time USART Pay attention to setting priorities .
The effect is , What characters do you send to SCM , He will return you any character , Display in serial assistant .
边栏推荐
- Write a simple memo using localstorage
- [don't bother to strengthen learning] video notes (IV) 2. Dqn realizes maze walking
- 力扣300-最长递增子序列——动态规划
- Problem: filesystemversionexception: you have version null and I want version 8
- Where is the bitbucket clone address
- [don't bother with intensive learning] video notes (III) 1. What is SARS?
- Centos7 install mysql8.0
- 云原生(十二) | Kubernetes篇之Kubernetes基础入门
- OPENCV学习DAY5
- [200 opencv routines] 236. Principal component analysis of feature extraction (openCV)
猜你喜欢

Write a simple memo using localstorage

Do you really understand the concept of buffer? Take you to uncover the buffer zone~

Add SSH key to bitbucket

Foreign lead operation takes one month to collect money, and the sideline still needs it

云原生(十二) | Kubernetes篇之Kubernetes基础入门

Raspberry Pie:: no space left on device
![[C language] implementation of three versions of address book small project (including source code)](/img/3b/926001332ec05378de4c35dc28ed55.png)
[C language] implementation of three versions of address book small project (including source code)

What's the difference between testing / developing programmers' professionalism and salted fish? They don't want to be excellent coders?

Spark Learning: a form of association in a distributed environment?

缓冲区的概念真的理解么?带你揭开缓冲区的面纱~
随机推荐
Learning transformer: overall architecture and Implementation
Vim: use tags file to extend the automatic code completion function of YCM for the third-party library of C language
Openstack network neutron knowledge point "openstack"
[don't bother to strengthen learning] video notes (II) 2. Write a small example of Q learning
Anti shake and throttling
This article takes you to understand the dynamic memory allocation of C language
Trie tree template 2
[Luogu p5829] [template] mismatch tree (string) (KMP)
JS string method
PHP debugging tool - how to install and use firephp
Li Kou 300 longest increasing subsequence dynamic programming
MySQL query database capacity size
[MySQL] - deep understanding of index
What is the cloud native mid platform business architecture?
System a uses window.open to call system B, and system B carries data back to system a after processing the business
error: field ‘XXX’ declared as a function
Scala learning: why emphasize immutable objects?
Raspberry Pie:: no space left on device
Build practical product help documents to improve user satisfaction
Cess test online line! The first decentralized storage network to provide multiple application scenarios