串口配置的一般步骤:
硬件:STM32F103ZET6(正点原子)
1.串口时钟使能,GPIO时钟使能:RCC_APB2PeriphClockCmd();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//GPIO使能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//串口使能
2.GPIO端口模式设置:GPIO_Init(); 模式设置为GPIO_Mode_AF_PP
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; //GPIO初始化
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING; //GPIO初始化
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);
3.串口参数初始化:USART_Init();
USART_InitStruct.USART_BaudRate = 115200; //串口初始化
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_Init(USART1,&USART_InitStruct);
4.使能串口:USART_Cmd();
USART_Cmd(USART1,ENABLE); //使能串口
5.开启中断并且初始化NVIC(如果需要开启中断才需要这个步骤)
NVIC_Init();
USART_ITConfig();
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//开启接收中断
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);
6.编写中断处理函数:USARTx_IRQHandler();
void USART1_IRQHandler(void)
{
int a = 0;
if(USART_GetITStatus(USART1,USART_IT_RXNE))
{
a = USART_ReceiveData(USART1);
USART_SendData(USART1,a);
}
}
串口数据收发:
void USART_SendData();//发送数据到串口,DR
uint16_t USART_ReceiveData();//接受数据,从DR读取接受到的数据
串口传输状态获取:
FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG);
void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint16_t USART_IT);