From 19ae0eb4d437eff9efa54bb14de636006f94b13c Mon Sep 17 00:00:00 2001
From: Cristian Maglie <c.maglie@arduino.cc>
Date: Fri, 24 Jun 2016 15:59:57 +0200
Subject: [PATCH] USB-CDC: access to rx buffer is now ISR-protected

---
 cores/arduino/USB/CDC.cpp | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/cores/arduino/USB/CDC.cpp b/cores/arduino/USB/CDC.cpp
index 6ae5e658..e6fc4a5b 100644
--- a/cores/arduino/USB/CDC.cpp
+++ b/cores/arduino/USB/CDC.cpp
@@ -214,24 +214,24 @@ int Serial_::read(void)
 {
 	ring_buffer *buffer = &cdc_rx_buffer;
 
+	uint8_t enableInterrupts = ((__get_PRIMASK() & 0x1) == 0);
+	__disable_irq();
+
 	// if we have enough space enable OUT endpoint to receive more data
 	if (stalled && availableForStore() >= EPX_SIZE)
 	{
 		stalled = false;
 		usb.epOut(CDC_ENDPOINT_OUT);
 	}
-	if (buffer->head == buffer->tail && !buffer->full)
-	{
-		return -1;
-	}
-	else
+	int c = -1;
+	if (buffer->head != buffer->tail || buffer->full)
 	{
-		unsigned char c = buffer->buffer[buffer->tail];
+		c = buffer->buffer[buffer->tail];
 		buffer->tail = (uint32_t)(buffer->tail + 1) % CDC_SERIAL_BUFFER_SIZE;
 		buffer->full = false;
-
-		return c;
 	}
+	if (enableInterrupts) __enable_irq();
+	return c;
 }
 
 void Serial_::flush(void)
-- 
GitLab