上代码:
/*
* 串口1 初始化
*/
void USART1_Initial(void)
{
USART_InitTypeDef USART_InitStruct;
GPIO_InitTypeDef GPIO_InitStructure;
// 设置复用到串口的IO口 PA10 PA11
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //USART1 TX
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA, &GPIO_InitStructure); //A端口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //USART1 RX
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //复用开漏输入
GPIO_Init(GPIOA, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//
USART_DeInit(USART1); //首要复位
/*!< This member configures the USART communication baud rate.
The baud rate is computed using the following formula:
– IntegerDivider = ((PCLKx) / (16 * (USART_InitStruct->USART_BaudRate)))
– FractionalDivider = ((IntegerDivider – ((u32) IntegerDivider)) * 16) + 0.5 */
USART_InitStruct.USART_BaudRate=2400;
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_Rx|USART_Mode_Tx;
USART_InitStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_Init(USART1, &USART_InitStruct);
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE); //USART1 接纳中止使能
USART_Cmd(USART1,ENABLE); // USART1 模块使能
}
中止服务程序部分:
void USART1_IRQHandler(void)
{
ITStatus ItState=RESET;
ItState=USART_GetITStatus(USART1,USART_IT_RXNE);
if(ItState==SET)
{
ReceivedData=USART_ReceiveData(USART1);// 发送收到的数据
ReceiveFlag=1;
//USART_SendData(USART1,ReceivedData);// 注释掉,放到主函数中异步发送试试
USART_ClearITPendingBit(USART1,USART_IT_RXNE); // 铲除标志位
}
}
程序的原意是 将收到的数据原样发送回去。

运用USART_SendData()函数非接连发送单个字符是没有问题的;当接连发送字符时(两个字符间没有延时),就会发现发送缓冲区有溢出现象。若发送的数据量很小时,此刻串口发送的仅仅最终一个字符,当发送数据量大时,就会导致发送的数据不可思议的丢掉。
如:
1
2
|
for(TxCounter = 0;TxCounter RxCounter; TxCounter++)
USART_SendData(USART1, RxBuffer[TxCounter]);
|