Skip to content

Commit 6ab2a9f

Browse files
Peter Van Hoyweghendamellis
Peter Van Hoyweghen
authored andcommitted
Avoid serial buffer overrun on leonardo
1 parent e2b9920 commit 6ab2a9f

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

hardware/arduino/cores/arduino/CDC.cpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,16 +141,22 @@ void Serial_::end(void)
141141
void Serial_::accept(void)
142142
{
143143
ring_buffer *buffer = &cdc_rx_buffer;
144-
int c = USB_Recv(CDC_RX);
145144
int i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE;
146145

147146
// if we should be storing the received character into the location
148147
// just before the tail (meaning that the head would advance to the
149148
// current location of the tail), we're about to overflow the buffer
150149
// and so we don't write the character or advance the head.
151-
if (i != buffer->tail) {
150+
151+
// while we have room to store a byte
152+
while (i != buffer->tail) {
153+
int c = USB_Recv(CDC_RX);
154+
if (c == -1)
155+
break; // no more data
152156
buffer->buffer[buffer->head] = c;
153157
buffer->head = i;
158+
159+
i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE;
154160
}
155161
}
156162

hardware/arduino/cores/arduino/USBCore.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -603,7 +603,7 @@ ISR(USB_GEN_vect)
603603
{
604604
#ifdef CDC_ENABLED
605605
USB_Flush(CDC_TX); // Send a tx frame if found
606-
while (USB_Available(CDC_RX)) // Handle received bytes (if any)
606+
if (USB_Available(CDC_RX)) // Handle received bytes (if any)
607607
Serial.accept();
608608
#endif
609609

0 commit comments

Comments
 (0)