串口空闲中断接收不定长数据
空闲中断是接受数据后出现一个byte的高电平(空闲)状态,就会触发空闲中断.并不是空闲就会一直中断,准确的说应该是上升沿(停止位)后一个byte,如果一直是低电平是不会触发空闲中断的(会触发break中断)。 串口初始化部分采用stm32cubemx软件生成。 一、串口空闲中断加DMA方式接收
在串口初始化时开启空闲中断和DMA接收
#define BUFFER_SIZE 512
volatile int rx_len=0;
volatile uint8_t recv_end_flag= 0;
uint8_t rx_buffer[BUFFER_SIZE]={0};
uint8_t rx_count=0;
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
__HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);
HAL_UART_Receive_DMA(&huart1, (uint8_t*)rx_buffer, BUFFER_SIZE);
}
void UART_IRQ(UART_HandleTypeDef *huart)
{
uint8_t ret = 0;
if(huart->Instance == USART1)
{
if(__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET)
{
recv_end_flag = 1;
__HAL_UART_CLEAR_IDLEFLAG(&huart1);
HAL_UART_DMAStop(&huart1);
rx_len =BUFFER_SIZE - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
HAL_UART_Receive_DMA(&huart1, (uint8_t*)rx_buffer, BUFFER_SIZE);
}
}
}
串口中断函数
extern void UART_IRQ(UART_HandleTypeDef *huart);
void USART1_IRQHandler(void)
{
HAL_UART_IRQHandler(&huart1);
UART_IRQ(&huart1);
}
二、串口空闲中断加接收中断方式` 初始化时开启空闲和接收中断
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
__HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);
__HAL_UART_ENABLE_IT(&huart1,UART_IT_RXNE);
}
void UART_IRQ(UART_HandleTypeDef *huart)
{
if(__HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE) != RESET)
{
if(recv_end_flag == UART_RX_STATE_READY)
{
__HAL_UART_ENABLE_IT(huart, UART_IT_IDLE);
recv_end_flag = UART_RX_STATE_START;;
rx_len = 0;
rx_buffer[rx_len] = huart->Instance->DR;
rx_len++;
}
else if(recv_end_flag == UART_RX_STATE_START)
{
rx_buffer[rx_len] = huart->Instance->DR;
rx_len++;
}
__HAL_UART_CLEAR_FLAG(huart, UART_FLAG_RXNE);
}
if(__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) != RESET)
{
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
__HAL_UART_DISABLE_IT(huart, UART_IT_IDLE);
recv_end_flag = UART_RX_STATE_DEAL;
}
}
三、数据处理
****
while(1)
{
if(recv_end_flag == 1)
{
Debugprintf("接收到数据个数:%d\r\n",rx_len);
HAL_UART_Transmit(&huart3, rx_buffer, rx_len, 1000);
rx_len = 0;
recv_end_flag = 0;
memset(rx_buffer, 0, BUFFER_SIZE);
}
}
****
while(1)
{
if(end_flag ==UART_RX_STATE_DEAL)
{
end_flag = UART_RX_STATE_READY;
HAL_UART_Transmit(&huart1, (uint8_t*)rec_buff, rx_cnt, 0XFFFF);
while(HAL_UART_GetState(&huart1) == HAL_UART_STATE_BUSY);
rx_cnt = 0;
memset(rec_buff, 0, sizeof(rec_buff));
__HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE);
__HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
}
}
}
|