diff --git a/src/application.cpp b/src/application.cpp index 23e6b99..6281229 100644 --- a/src/application.cpp +++ b/src/application.cpp @@ -227,6 +227,8 @@ bool Application::CheckMsgs() { while (modules::serial::Available()) { switch (protocol.DecodeRequest(modules::serial::ConsumeByte())) { case mpd::MessageCompleted: + // Discard any unread data + modules::serial::Reset(); // process the input message return true; break; diff --git a/src/hal/avr/usart.cpp b/src/hal/avr/usart.cpp index fd6f411..4bf2e6e 100644 --- a/src/hal/avr/usart.cpp +++ b/src/hal/avr/usart.cpp @@ -14,6 +14,16 @@ uint8_t USART::Read() { return c; } +void USART::ResetReceiver() +{ + // Disable/Enable Receiver to discard pending bytes + husart->UCSRxB &= ~(1 << 4); + husart->UCSRxB |= (1 << 4); + + // Reset circular buffer, head = tail + rx_buf.reset(); +} + void USART::Write(uint8_t c) { _written = true; // If the buffer and the data register is empty, just write the byte diff --git a/src/hal/circular_buffer.h b/src/hal/circular_buffer.h index a76b1de..cf7ac16 100644 --- a/src/hal/circular_buffer.h +++ b/src/hal/circular_buffer.h @@ -31,6 +31,11 @@ public: return ((index_t)(head - tail) % (size * 2)) == size; } + /// Reset the circular buffer to empty + inline void reset() { + head = tail; + } + /// Advance the head index of the buffer. /// No checks are performed. full() needs to be queried beforehand. inline void push() { @@ -101,6 +106,11 @@ public: return index.full(); } + /// Reset the circular buffer to empty + inline void reset() { + index.reset(); + } + /// Insert an element into the buffer. /// Checks for empty spot for the element and does not change the buffer content /// in case the buffer is full. diff --git a/src/hal/usart.h b/src/hal/usart.h index dc23803..5635490 100644 --- a/src/hal/usart.h +++ b/src/hal/usart.h @@ -44,6 +44,9 @@ public: /// @returns current character from the UART and extracts it from the read buffer uint8_t Read(); + /// Discard all pending data from the receiver + void ResetReceiver(); + /// @param c character to be pushed into the TX buffer (to be sent) void Write(uint8_t c); /// @param str pointer to a string in RAM to be pushed byte-by-byte into the TX buffer (to be sent) diff --git a/src/modules/serial.cpp b/src/modules/serial.cpp index 4b3b26e..85c6dab 100644 --- a/src/modules/serial.cpp +++ b/src/modules/serial.cpp @@ -32,6 +32,10 @@ uint8_t ConsumeByte() { return hu::usart1.Read(); } +void Reset() { + hu::usart1.ResetReceiver(); +} + } // namespace serial } // namespace modules diff --git a/src/modules/serial.h b/src/modules/serial.h index c50bd3a..5cce0af 100644 --- a/src/modules/serial.h +++ b/src/modules/serial.h @@ -12,6 +12,8 @@ bool Available(); uint8_t ConsumeByte(); +void Reset(); + } // namespace serial } // namespace modules