STM32 HAL UART循环发送缓存

 •  Filed under Embedded
#define UART_SEND_BUFF_SIZE		100
uint8_t UARTSendBuff[UART_SEND_BUFF_SIZE + 2] = {0};
uint16_t UARTSendBuffDataPos = 0;
uint16_t UARTSendBuffUsedPos = 0;
uint8_t UARTSendBuff_FlagSendBusy = 0;
void UARTSendBuff_putData(uint8_t * data,uint16_t len){
    while(len){
        UARTSendBuffDataPos++;
        if(UARTSendBuffDataPos > UART_SEND_BUFF_SIZE){
            UARTSendBuffDataPos = 1;
        }
        UARTSendBuff[UARTSendBuffDataPos] = *data;

        len --;
        data++;
    }
}

void UARTSendBuff_StartSend(){
    if(UARTSendBuff_FlagSendBusy == 0){
        if(UARTSendBuffDataPos == UARTSendBuffUsedPos){
            return;
        }else if(UARTSendBuffDataPos > UARTSendBuffUsedPos){
            UARTSendBuff_FlagSendBusy = 1;
            HAL_UART_Transmit_IT(&huart2,&UARTSendBuff[UARTSendBuffUsedPos + 1],(UARTSendBuffDataPos-UARTSendBuffUsedPos));
            UARTSendBuffUsedPos = UARTSendBuffDataPos;
        }else if(UARTSendBuffDataPos < UARTSendBuffUsedPos){
            if(UARTSendBuffUsedPos == UART_SEND_BUFF_SIZE){
                UARTSendBuffUsedPos = 0;
                UARTSendBuff_FlagSendBusy = 1;
                HAL_UART_Transmit_IT(&huart2,&UARTSendBuff[UARTSendBuffUsedPos + 1],(UARTSendBuffDataPos-UARTSendBuffUsedPos));
                UARTSendBuffUsedPos = UARTSendBuffDataPos;
            }else{
                UARTSendBuff_FlagSendBusy = 1;
                HAL_UART_Transmit_IT(&huart2,&UARTSendBuff[UARTSendBuffUsedPos + 1],(UART_SEND_BUFF_SIZE-UARTSendBuffUsedPos));
                UARTSendBuffUsedPos = 0;
            }
        }
    }
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart){
    UARTSendBuff_FlagSendBusy = 0;
    UARTSendBuff_StartSend();
}

void UARTSEndBuff_Send(uint8_t * data,uint16_t len){
    UARTSendBuff_putData(data,len);
    UARTSendBuff_StartSend();
}