公司网站制作天强科技专业购物网站建设多少钱
文章目录
- 一、STM32串口常用寄存器和库函数
 - 1.1 常用的串口寄存器
 - 1.2 串口相关的库函数
 - 1.3 状态寄存器(USART_ SR)
 - 1.4 数据寄存器(USART_ DR)
 - 1.5 波特率寄存器(USART_BRR)
 
- 二、串口配置一般步骤
 
一、STM32串口常用寄存器和库函数
1.1 常用的串口寄存器
USART_ SR状态寄存器
 USART_ DR数据寄存器
 USART_BRR波特率寄存器
1.2 串口相关的库函数
void USART_ Init();           //串口初始化:波特率,数据字长,奇偶校验,硬件流控以及收发使能
void USART Cmd();             //使能串口
void USART ITConfig0;         //使能相关中断void USART SendData();        //发送数据到串口,DR
uint16 t USART ReceiveData(); //接受数据,从DR读取接受到的数据FlagStatus USART GetFlagStatus(); //获取状态标志位
void USART ClearFlag();           //清除状态标志位
ITStatus USART GetlTStatus);      //获取中断状态标志位
void USART_ ClearlTPendingBit);   //清除中断状态标志位 
1.3 状态寄存器(USART_ SR)

所用函数
FlagStatus USART_GetFlagStatus(USART TypeDef USARTx; uint16 t USART_FLAG);
FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG)
{FlagStatus bitstatus = RESET;/* Check the parameters */assert_param(IS_USART_ALL_PERIPH(USARTx));assert_param(IS_USART_FLAG(USART_FLAG));/* The CTS flag is not available for UART4 and UART5 */if (USART_FLAG == USART_FLAG_CTS){assert_param(IS_USART_1236_PERIPH(USARTx));} if ((USARTx->SR & USART_FLAG) != (uint16_t)RESET){bitstatus = SET;}else{bitstatus = RESET;}return bitstatus;
}
 
1.4 数据寄存器(USART_ DR)

相关函数
void USART SendData(USART TypeDef* USARTx, uint16 t Data);
uint16_t USART_ ReceiveData(USARTTypeDef* USARTx)
void USART_SendData(USART_TypeDef* USARTx, uint16_t Data)
{/* Check the parameters */assert_param(IS_USART_ALL_PERIPH(USARTx));assert_param(IS_USART_DATA(Data)); /* Transmit Data */USARTx->DR = (Data & (uint16_t)0x01FF);
} 
uint16_t USART_ReceiveData(USART_TypeDef* USARTx)
{/* Check the parameters */assert_param(IS_USART_ALL_PERIPH(USARTx));/* Receive Data */return (uint16_t)(USARTx->DR & (uint16_t)0x01FF);
}
 
1.5 波特率寄存器(USART_BRR)

关于波特率的计算
小数部分需要乘上16
void USART Init(USART TypeDef* USARTx; USART_ InitTypeDef* USART: InitStruct)
 第一个入口参数是用来确实是哪个串口
#define IS_USART_ALL_PERIPH(PERIPH) (((PERIPH) == USART1) || \((PERIPH) == USART2) || \((PERIPH) == USART3) || \((PERIPH) == UART4)  || \((PERIPH) == UART5)  || \((PERIPH) == USART6) || \((PERIPH) == UART7)  || \((PERIPH) == UART8)) 1-8个
 
第二个入口参数结构体,就是设置串口的一些变量
typedef struct
{uint32_t USART_BaudRate;            //设置波特率uint16_t USART_WordLength;          //设置字长,8/9uint16_t USART_StopBits;            //停止位uint16_t USART_Parity;              //奇偶校验uint16_t USART_Mode;                //使能发送/控制uint16_t USART_HardwareFlowControl; //硬件控制(本次不用)
} USART_InitTypeDef;
 
二、串口配置一般步骤
①串口时钟使能: RCC_APBxPeriphClockCmd);
 GPIO时钟使能: RCC_ AHB1PeriphClockCmd();
②引脚复用映射:GPIO_PinAFConfig();
③GPIO端口模式设置:GPIO _Init(); 模式设置为GPIO_Mode_ AF
④串口参数初始化: USART_ Init();
⑤开启中断并且初始化NVIC ( 如果需要开启中断才需要这个步骤)
 NVIC_ Init();
 USART_ITConfig();
⑥使能串口:USART_Cmd();
⑦编写中断处理函数: USARTX_ IRQHandler();
⑧串口数据收发:
 void USART_SendData();//发送数据到串口,DR
 uint16_ t USART_ReceiveData();//接受数据,从DR读取接受到的数据
⑨串口传输状态获取:
 FlagStatus USART_GetFlagStatus();
 void USART_ClearlTPendingBit();

