一、简述
本文介绍的是一个.c文件中的内容,主要功能为STM32F101C8T6中USART1的初始化、配置、中断接收以及发送函数。
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_usart.h"
u8 USART1_RX_Buff[4] = {0x00, 0x00, 0x00, 0x00};
u8 USART1_RX_Count = 0;
二、USART1初始化与配置
void USART1_Init(u32 bound){
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
USART_DeInit(USART1);
//USART1_TX GPIOA.9
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA,&GPIO_InitStructure);
//USART1_RX GPIOA.10
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_Init(GPIOA,&GPIO_InitStructure);
//Usart1 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //子优先级0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//USART 初始化设置
USART_InitStructure.USART_BaudRate = bound;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_WordLength = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //开启串口接受中断
USART_Cmd(USART1, ENABLE); //使能串口1
}
三、中断接收函数
void USART1_IRQHandler(){
u8 Temp;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET){
Temp = USART_ReceiveData(USART1); //读取接收到的数据
if(USARTx_RX_Count < 4){
USARTx_RX_Buff[USARTx_RX_Count] = Temp;
USARTx_RX_Count++;
}
}
//溢出-如果发生溢出需要先读SR,再读DR寄存器则可清除不断入中断的问题
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) != SET){
USART_ReceiveData(USART1);
USART_ClearFlag(USART1, USART_FLAG_ORE);
}
USART_ClearFlag(USART1, USART_IT_RXNE); //一定要清除接收中断
}
四、发送函数
void USART1_TxChar(int ch){
USART_SendData(USART1, (u8)ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
void USART1_TxStr(char *pt){
while(*pt != '\0'){
USARTx_TxChar(*pt);
pt++;
}
}
void USART1_TxCharBuff(u8 buf[], u32 len){
u32 i;
for(i = 0; i < len; i++){
USARTx_TxChar(buf[i]);
}
}