综合利用串口中断和定时器
可以利用定时器,判断超时。如果超时,就把接收计数清零并将接收数组index清零,重新开始新一轮接收。
以下是部分代码(有点乱,慢慢看):
vu8 tim4_overrun = (u8)0x00;
vu8 tim4_of_10ms = (u8)0x00;//tim4_overrun_flag 10ms
@far @interrupt void TIM4_IR(void)
{
TIM4->SR1 &= ~TIM4_SR1_UIF;
if (++tim4_overrun > (u8)10)
{
tim4_of_10ms |= (u8)0x01;
tim4_overrun &= (u8)0x00;
}
return;
}
@far @interrupt void USART_RX(void)
{
u8 dummy;
//如果没有通讯错误,且接收寄存器非空
if (!(UART1->SR & 0X0f))
{
TIM4->CNTR &= (u8)0x00;
tim4_overrun &=(u8)0x00;
if (tim4_of_10ms)
{
RxCounter &= (u8)0x00;
tim4_of_10ms &= (u8)0x00;
}
TxBuffer[RxCounter++] = UART1->DR;
if (RxCounter >= BufferSize)
{
while((UART1->SR & 0x20))//等待接收标志清空
{
dummy = UART1->DR;
}
RxCounter = 0;
}
}
else//如果有通讯错误
{
LEDS_PORT->ODR ^= 0x40;
RxCounter = 0;
dummy = UART1->SR;
dummy = UART1->DR;
}
return;
}
//void main(void)中
while (1) //等待中断
{
if (tim4_of_10ms)
{
RxCounter = 0;
tim4_of_10ms = 0;
}
}
|