当前位置:网站首页>[STM32 learning] (6) use of serial port 1 (usart1)
[STM32 learning] (6) use of serial port 1 (usart1)
2022-07-24 09:50:00 【Use small materials】
SCM serial port must be learned , And it's important , It is very important in data transmission and program debugging .
This blog first learns USART1 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 :

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
uart1_init(9600); // The serial port is initialized to 9600
//LED_Init(); //LED Port initialization
//KEY_Init(); // Initialize the hardware interface connected with the key
//GPIO_Write(GPIOA,0X00F0);
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(USART1, USART_RX_BUF[t]);// Serial port 1 send data
while(USART_GetFlagStatus(USART1,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 wan tin \r\n");
printf("come on!! \r\n\r\n");
}
if(times%200==0)printf(" Please input data , End with enter \n");
if(times%30==0)LED1=!LED1;// flashing LED, Indicates that the system is running .
delay_ms(10);
}
}
}
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(USART1,USART_FLAG_TC)==RESET);
USART_SendData(USART1,(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
// initialization IO A serial port 1
//bound: Baud rate
void uart1_init(u32 bound){
//GPIO Port settings
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); // Can make USART1,GPIOA The clock
USART_DeInit(USART1); // Reset serial port 1
//USART1_TX PA.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 PA9
//USART1_RX PA.10
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;// Floating input
GPIO_Init(GPIOA, &GPIO_InitStructure); // initialization PA10
//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(USART1, &USART_InitStructure); // Initialize serial port
#if EN_USART1_RX // If enabled, receive
//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
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);// Open interrupt
#endif
USART_Cmd(USART1, ENABLE); // Enable serial port
}
void USART1_IRQHandler(void) // A serial port 1 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(USART1, USART_IT_RXNE) != RESET) // Receive interrupt ( The data received must be 0x0d 0x0a ending )
{
Res =USART_ReceiveData(USART1);//(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
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 uart1_init(u32 bound);
void uart2_init(u32 bound);
void uart3_init(u32 bound);
void uart4_init(u32 bound);
void uart5_init(u32 bound);
#endif
sys.c
#include "sys.h"
void NVIC_Configuration(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); // Set up NVIC Interrupt grouping 2:2 Bit preemption priority ,2 Bit response priority
}
sys.h
#ifndef __SYS_H
#define __SYS_H
#include "stm32f10x.h"
//
//
//0, I won't support it ucos
//1, Support ucos
#define SYSTEM_SUPPORT_UCOS 0 // Define whether the system folder supports UCOS
// Bit band operation , Realization 51 Allied GPIO Control function
// The concrete realization idea , Reference resources <<CM3 Authoritative guide >> The fifth chapter (87 page ~92 page ).
//IO Port operation macro definition
#define BITBAND(addr, bitnum) ((addr & 0xF0000000)+0x2000000+((addr &0xFFFFF)<<5)+(bitnum<<2))
#define MEM_ADDR(addr) *((volatile unsigned long *)(addr))
#define BIT_ADDR(addr, bitnum) MEM_ADDR(BITBAND(addr, bitnum))
//IO Port address mapping
#define GPIOA_ODR_Addr (GPIOA_BASE+12) //0x4001080C
#define GPIOB_ODR_Addr (GPIOB_BASE+12) //0x40010C0C
#define GPIOC_ODR_Addr (GPIOC_BASE+12) //0x4001100C
#define GPIOD_ODR_Addr (GPIOD_BASE+12) //0x4001140C
#define GPIOE_ODR_Addr (GPIOE_BASE+12) //0x4001180C
#define GPIOF_ODR_Addr (GPIOF_BASE+12) //0x40011A0C
#define GPIOG_ODR_Addr (GPIOG_BASE+12) //0x40011E0C
#define GPIOA_IDR_Addr (GPIOA_BASE+8) //0x40010808
#define GPIOB_IDR_Addr (GPIOB_BASE+8) //0x40010C08
#define GPIOC_IDR_Addr (GPIOC_BASE+8) //0x40011008
#define GPIOD_IDR_Addr (GPIOD_BASE+8) //0x40011408
#define GPIOE_IDR_Addr (GPIOE_BASE+8) //0x40011808
#define GPIOF_IDR_Addr (GPIOF_BASE+8) //0x40011A08
#define GPIOG_IDR_Addr (GPIOG_BASE+8) //0x40011E08
//IO Mouth operation , Only for single IO mouth !
// Make sure n The value is less than 16!
#define PAout(n) BIT_ADDR(GPIOA_ODR_Addr,n) // Output
#define PAin(n) BIT_ADDR(GPIOA_IDR_Addr,n) // Input
#define PBout(n) BIT_ADDR(GPIOB_ODR_Addr,n) // Output
#define PBin(n) BIT_ADDR(GPIOB_IDR_Addr,n) // Input
#define PCout(n) BIT_ADDR(GPIOC_ODR_Addr,n) // Output
#define PCin(n) BIT_ADDR(GPIOC_IDR_Addr,n) // Input
#define PDout(n) BIT_ADDR(GPIOD_ODR_Addr,n) // Output
#define PDin(n) BIT_ADDR(GPIOD_IDR_Addr,n) // Input
#define PEout(n) BIT_ADDR(GPIOE_ODR_Addr,n) // Output
#define PEin(n) BIT_ADDR(GPIOE_IDR_Addr,n) // Input
#define PFout(n) BIT_ADDR(GPIOF_ODR_Addr,n) // Output
#define PFin(n) BIT_ADDR(GPIOF_IDR_Addr,n) // Input
#define PGout(n) BIT_ADDR(GPIOG_ODR_Addr,n) // Output
#define PGin(n) BIT_ADDR(GPIOG_IDR_Addr,n) // Input
void NVIC_Configuration(void);
#endif
delay.c and delay.h The document is not provided here , Because there are few delay functions used in the serial port .
The effect is , What characters do you send to SCM , He will return you any character , Display in serial assistant .
边栏推荐
- Scarcity in Web3: how to become a winner in a decentralized world
- Li Kou 300 longest increasing subsequence dynamic programming
- Hucang integrated e-commerce project (I): introduction to the project background and structure
- Calculate CPU utilization [Prometheus]
- Es document CRUD
- ASI-20220222-Implicit PendingIntent
- Boundless dialogue | participate in the live broadcast on July 25 and win the prize
- Will your NFT disappear? Dfinity provides the best solution for NFT storage
- LeetCode刷题系列-- 174. 地下城游戏
- IdentityServer4入门
猜你喜欢

Detailed LinkedList
![[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?](/img/57/0ebff0839d2a2898472d3270fd13df.png)
[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?

力扣300-最长递增子序列——动态规划

Getting started with web security - open source firewall pfsense installation configuration
![[MySQL] - deep understanding of index](/img/a6/6ca1356fe11bd33ec7362ce7cdc652.png)
[MySQL] - deep understanding of index

Understanding of magnetic parameters in Hall sensors

Raspberry Pie: serial port login does not display print information

An article takes you to understand the operation of C language files in simple terms
![[don't bother to strengthen learning] video notes (IV) 1. What is dqn?](/img/74/51219a19595f93e7a85449f54d354d.png)
[don't bother to strengthen learning] video notes (IV) 1. What is dqn?
![[don't bother with reinforcement learning] video notes (I) 2. Summary of reinforcement learning methods](/img/7e/cb5bf37de4482facda723f3de7deb6.jpg)
[don't bother with reinforcement learning] video notes (I) 2. Summary of reinforcement learning methods
随机推荐
《动手学深度学习》(七) -- 边界框和锚框
Vim: use tags file to extend the automatic code completion function of YCM for the third-party library of C language
Gin framework uses session and redis to realize distributed session & Gorm operation mysql
MySQL query database capacity size
Add SSH key to bitbucket
Spark Learning: how to choose different association forms and mechanisms?
Openstack network neutron knowledge point "openstack"
PHP Basics - session control - Session
Dark king | analysis of zego low illumination image enhancement technology
How does SRE and development of Google cooperate
Dorissql syntax Usage Summary
[MySQL] - deep understanding of index
S2b2b system standardizes the ordering and purchasing process and upgrades the supply chain system of household building materials industry
Raspberry Pie: /bin/sh: 1: bison: not found
Detailed LinkedList
Spark Learning: Spark implementation of distcp
Write a simple memo using localstorage
Build practical product help documents to improve user satisfaction
Will your NFT disappear? Dfinity provides the best solution for NFT storage
Racecar multi-point navigation experiment based on ROS communication mechanism