/////////////////////////////////////////////////////头文件部分///////////////////////////////////////////////////////////////////////////////
#define EMPTY 0xFFFF
#define TIMEOUT 0xFFFF
#define UART2_RBUF_SIZE 256 //要求:2 的整次幂
#if UART2_RBUF_SIZE < 2
#error UART2_RBUF_SIZE is too small. It must be larger than 1.
#elif ((UART2_RBUF_SIZE & (UART2_RBUF_SIZE-1)) != 0)
#error UART2_RBUF_SIZE must be a power of 2.
#endif
typedef struct uart2_rbuf_st
{
unsigned int in; //输入
unsigned int out; //输出
unsigned char buf [UART2_RBUF_SIZE]; //缓冲区空间
}UART2_RBUF_ST;
extern UART2_RBUF_ST uart2_rbuf;
uint16_t USART2_GetCharBlock(uint16_t timeout);
uint16_t USART2_GetChar(void);
//////////////////////////////////////////////////////c代码部分////////////////////////////////////////////////////////////////////////////////
/**********************************************************************************
* 串口1接收字符函数,阻塞模式(接收缓冲区中提取)
**********************************************************************************/
uint16_t USART2_GetCharBlock(uint16_t timeout)
{
UART2_RBUF_ST *p = &uart2_rbuf;
uint16_t to = timeout;
while((p->in - p->out) == 0)if(!(--to))return TIMEOUT;
return (p->buf [(p->out++) & (UART2_RBUF_SIZE - 1)]);
}
/**********************************************************************************
* 串口1接收字符函数,非阻塞模式(接收缓冲区中提取)
**********************************************************************************/
uint16_t USART2_GetChar(void)
{
UART2_RBUF_ST *p = &uart2_rbuf;
if((p->in - p->out) == 0) //缓冲区空条件
return EMPTY;
return USART2_GetCharBlock(1000);
}
//printf定义
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&Usart2Handle, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
///////////////////////////////////////////////////中断处理部分/////////////////////////////////////////////////////////////////////////////////
void USART2_IRQHandler(void)
{
uint8_t d;
UART2_RBUF_ST *p = &uart2_rbuf;
/* UART in mode Receiver ---------------------------------------------------*/
//if((__HAL_UART_GET_IT(&Usart2Handle, UART_IT_RXNE) != RESET) && (__HAL_UART_GET_IT_SOURCE(&Usart2Handle, UART_IT_RXNE) != RESET))
if((__HAL_UART_GET_IT(&Usart2Handle, UART_IT_RXNE) != RESET))
{
d = (uint8_t)(Usart2Handle.Instance->RDR);
if((p->in - p->out)<UART2_RBUF_SIZE)
{
p->buf [p->in & (UART2_RBUF_SIZE-1)] = d;
p->in++;
}
while(HAL_IS_BIT_SET(Usart2Handle.Instance->ISR, UART_FLAG_RXNE));//清楚中断标志
}
HAL_UART_IRQHandler(&Usart2Handle);
}
|