From e008cc8da151fae30760fbe4cae4c9cb9984d554 Mon Sep 17 00:00:00 2001 From: BlackMark Date: Wed, 25 May 2016 01:40:53 +0200 Subject: [PATCH] Fixed flushing receive buffer to work independent of baud rate and with and without interrupts --- usart.cpp | 41 ++++++++++++++++++++++++++++++++++------- usart.h | 4 ++-- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/usart.cpp b/usart.cpp index b451df5..82d72cf 100644 --- a/usart.cpp +++ b/usart.cpp @@ -300,7 +300,7 @@ bool USART0::receiveByte( uint8_t &ui8Data, uint16_t ui16TimeoutMS ) { _delay_ms( 1 ); - if( ui16DelayCounter++ >= ui16TimeoutMS ) + if( ui16DelayCounter++ > ui16TimeoutMS ) { return false; } @@ -336,14 +336,41 @@ void USART0::flushReceive() { uint8_t ui8Received; - while( m_vsizeRXBufferHead != m_vsizeRXBufferTail ) - { - receiveByte( ui8Received ); - } + uint16_t ui16UBRR; + ui16UBRR = static_cast( *m_vui8pUBRRH ) << 8; + ui16UBRR |= *m_vui8pUBRRL; - if( !( SREG & ( 1 << SREG_I ) ) && ( *m_vui8pUCSRA & ( 1 << RXC_D ) ) ) + uint8_t ui8BitsPerSymbol = 10; + + uint16_t ui16BaudDelayMS = static_cast( ui8BitsPerSymbol * ( 16 * ( ui16UBRR + 1.0 ) ) / ( F_CPU / 1000.0 ) ) + 1; + + if( !( SREG & ( 1 << SREG_I ) ) ) { - ui8Received = *m_vui8pUDR; + while( true ) + { + for( uint16_t i = 0; i < ui16BaudDelayMS; ++i ) + { + _delay_ms( 1 ); + } + + if( m_vsizeRXBufferHead != m_vsizeRXBufferTail ) + { + receiveByte( ui8Received ); + continue; + } + + if( ( *m_vui8pUCSRA & ( 1 << RXC_D ) ) ) + { + ui8Received = *m_vui8pUDR; + continue; + } + + break; + } + } + else + { + while( receiveByte( ui8Received, ui16BaudDelayMS ) ); } } diff --git a/usart.h b/usart.h index 485347c..1d7ba01 100644 --- a/usart.h +++ b/usart.h @@ -1,7 +1,7 @@ /* * Copyright (c) by BlackMark 2015-2016 -* Date 24/05/2016 -* Version 2.9 +* Date 25/05/2016 +* Version 3.0 */ #ifndef USART_H