USART一般有查询和中断两种方式,不过我还是比较喜欢用查询的方法,因为中断的方法总是用不明白,觉得好深奥啊。折腾了好几天,我觉得配置串口很关键。
步骤一:初始化GPIO
GPIO_InitTypeDef GPIO_InitStructure;
/* Configure USART1 Tx (PA.09) as alternate function push-pull */
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);
/* Configure USART1 Rx (PA.10) as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure LED1 (PD.8) as output floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD, &GPIO_InitStructure);
步骤二:开时钟
/* Enable USART1, GPIOA, GPIOD and AFIO clocks */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD
| RCC_APB2Periph_AFIO, ENABLE);
在此说明,不用设置RCC_APB2Periph_AFIO也是可以的,也就是在此没有使用复用功能。
步骤三:初始化USART1
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = 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;
/* Configure USART1 */
USART_Init(USART1, &USART_InitStructure);
/* Enable USART1 Receive and Transmit interrupts */
/* Enable the USART1 */
USART_Cmd(USART1, ENABLE);
步骤四:实现串口通信
while (1)
{
GPIO_SetBits(GPIOA,GPIO_Pin_11); //接收状态
Rx_status = USART_GetFlagStatus(USART1,USART_FLAG_RXNE);
if(Rx_status == SET)
{
rec_temp = USART_ReceiveData(USART1);
GPIO_SetBits(GPIOA,GPIO_Pin_12); //leep_on
Delay(0xffff);
Delay(0xffff);
GPIO_ResetBits(GPIOA,GPIO_Pin_11);
USART_SendData(USART1,rec_temp);
while(USART_GetFlagStatus(USART1,USART_FLAG_TC) == RESET);
GPIO_ResetBits(GPIOA,GPIO_Pin_12);//leep_off
}
}
循环接收到上位机发过来的字符,然后再回传给上位机。