一定要看开发手册,先理清步骤,所有的函数和参数都可以再官方的文件里面找到。
1、时钟使能 2、GPIO_Init()函数,由该函数去找所需要的定义的变量和配置参数 3、USART_Init()
4、NVIC_Init(); 5、USART1_IRQHandler()
STM32其实最烦的就是这些参数的配置,当你知道用着个套路去设置后就简单多了。
各种参数的意思可以在后面写代码是慢慢搞懂。
#include "stm32f10x.h"
void myUart1Init();//串口中断初始化
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置中断分组,有四个分组
myUart1Init();
while(1);
}
void myUart1Init()
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
//1、使能GPIO口、外设USART时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);//PA9 PA10->APB2
// RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE);//PA9 PA10->APB2
//2、GPIO口配置
//PA9 Tx
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;//看手册确定这些参数
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_10MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);//注意:这一条和下面一条都要写
//PA10 Rx
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_10MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);
//3、串口参数设置
USART_InitStruct.USART_BaudRate=115200;
USART_InitStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode=USART_Mode_Tx|USART_Mode_Rx;
USART_InitStruct.USART_Parity=USART_Parity_No;
USART_InitStruct.USART_StopBits=USART_StopBits_1;
USART_InitStruct.USART_WordLength=USART_WordLength_8b;
USART_Init(USART1,&USART_InitStruct);//PA9 PA10 ->USART1
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能串口1中断,接收到数据就完成中断
USART_Cmd(USART1,ENABLE); //使能串口
//4、中断参数设置
NVIC_InitStruct.NVIC_IRQChannel=USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=1;
NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;
NVIC_Init(&NVIC_InitStruct);
}
//中断处理函数,触发中断时自动调用
void USART1_IRQHandler(void)
{
//typedef unsigned short int uint16_t;
//typedef unsigned char uint8_t;
uint16_t res;
if(USART_GetITStatus(USART1,USART_IT_RXNE))//判断接收数据状态
{
res=USART_ReceiveData(USART1);//接收数据
USART_SendData(USART1,res);//发送数据
}
}