stm32 串口連續(xù)接收 發(fā)送的出錯的問題
/*
* 串口1 初始化
*/
void USART1_Initial(void)
{
USART_InitTypeDef USART_InitStruct;
GPIO_InitTypeDef GPIO_InitStructure;
// 設(shè)置復(fù)用到串口的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; //復(fù)用推挽輸出
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; //復(fù)用開漏輸入
GPIO_Init(GPIOA, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//
USART_DeInit(USART1); //首先復(fù)位
/*!< 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);// 發(fā)送收到的數(shù)據(jù)
ReceiveFlag=1;
//USART_SendData(USART1,ReceivedData);// 注釋掉,放到主函數(shù)中異步發(fā)送試試
USART_ClearITPendingBit(USART1,USART_IT_RXNE); // 清除標志位
}
}
使用USART_SendData()函數(shù)非連續(xù)發(fā)送單個字符是沒有問題的;當連續(xù)發(fā)送字符時(兩個字符間沒有延時),就會發(fā)現(xiàn)發(fā)送緩沖區(qū)有溢出現(xiàn)象。若發(fā)送的數(shù)據(jù)量很小時,此時串口發(fā)送的只是最后一個字符,當發(fā)送數(shù)據(jù)量大時,就會導(dǎo)致發(fā)送的數(shù)據(jù)莫名其妙的丟失。
如:
1 2 | for(TxCounter = 0;TxCounter RxCounter; TxCounter++) USART_SendData(USART1, RxBuffer[TxCounter]); |
評論