串口选择
示例给出的是串口的,因为今天回老家,带的杜绑线是公对母的,不能接串口1,所以选择串口2,即PA2--TX,PA3--RX。
初始化串口
- 初始化UART2的时钟:__RCC_UART2_CLK_ENABLE();
- 初始化GPIOA外设时钟:RCC_AHBPeriphClk_Enable( RCC_AHB_PERIPH_GPIOA, ENABLE);
- 复用PA2为UART2TX: PA02_AFx_UART2TXD();
- 复用PA3为UART2RX:PA03_AFx_UART2RXD();
- 初始化PA2为高速输出模式:
GPIO_InitStructure.Pins = GPIO_PIN_2; //PA2
GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
- 初始化PA3为上拉输入:
GPIO_InitStructure.Pins = GPIO_PIN_3; //PA3
GPIO_InitStructure.Mode = GPIO_MODE_INPUT_PULLUP;
GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
- 初始化UART2配置为9600波特率:
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_Over = USART_Over_16;
USART_InitStructure.USART_Source = USART_Source_PCLK;
USART_InitStructure.USART_UclkFreq = 64000000;
USART_InitStructure.USART_StartBit = USART_StartBit_FE;
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;
USART_Init(CW_UART2, &USART_InitStructure);
- 使能中断输入
USART_ITConfig(CW_UART2, USART_IT_RC, ENABLE);
NVIC_SetPriority(UART2_IRQn, 0);
NVIC_EnableIRQ(UART2_IRQn);
- 中断接收函数,主要功能为判断接收到的第一位是否为0,第二位是否为1,如果总接收长度为4位,测翻转LED4,具体代码如下:
void UART2_IRQHandler(void)
{
unsigned char TxRxBuffer;
if(USART_GetITStatus(CW_UART2, USART_IT_RC) != RESET)
{
USART_ClearITPendingBit(CW_UART2, USART_IT_RC);
TxRxBuffer = USART_ReceiveData_8bit(CW_UART2);
rec[re_count]=TxRxBuffer;
if (re_count == 0&&rec[0]==0x00)
{
rev_start=1;
re_count++;
}
else if(rev_start==1)
{
if(re_count==1&&rec[1]!=0x01)
{
re_count=0;rev_start=0;
}
else if(re_count==4)
{check_flag=1;re_count=0;rev_start=0;}
else
re_count++;
}
}
}
实现效果,下载后,串口接收到0x00 0x01 0x02 0x03 ,HEX发送00 01 02 03 可以实现LED4的翻转:
|