Skip to content

Commit 8701c88

Browse files
committed
Improves UART reading performance
1 parent fd72cf4 commit 8701c88

File tree

3 files changed

+35
-13
lines changed

3 files changed

+35
-13
lines changed

cores/esp32/HardwareSerial.cpp

+6-13
Original file line numberDiff line numberDiff line change
@@ -450,10 +450,12 @@ int HardwareSerial::peek(void)
450450

451451
int HardwareSerial::read(void)
452452
{
453-
if(available()) {
454-
return uartRead(_uart);
453+
uint8_t c = 0;
454+
if (uartReadBytes(_uart, &c, 1, 0) == 1) {
455+
return c;
456+
} else {
457+
return -1;
455458
}
456-
return -1;
457459
}
458460

459461
// read characters into buffer
@@ -462,16 +464,7 @@ int HardwareSerial::read(void)
462464
// the buffer is NOT null terminated.
463465
size_t HardwareSerial::read(uint8_t *buffer, size_t size)
464466
{
465-
size_t avail = available();
466-
if (size < avail) {
467-
avail = size;
468-
}
469-
size_t count = 0;
470-
while(count < avail) {
471-
*buffer++ = uartRead(_uart);
472-
count++;
473-
}
474-
return count;
467+
return uartReadBytes(_uart, buffer, size, 0);
475468
}
476469

477470
void HardwareSerial::flush(void)

cores/esp32/esp32-hal-uart.c

+28
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,34 @@ uint32_t uartAvailableForWrite(uart_t* uart)
326326
return available;
327327
}
328328

329+
size_t uartReadBytes(uart_t* uart, uint8_t *buffer, size_t size, uint32_t timeout_ms)
330+
{
331+
if(uart == NULL || size == 0 || buffer == NULL) {
332+
return 0;
333+
}
334+
335+
size_t bytes_read = 0;
336+
337+
UART_MUTEX_LOCK();
338+
339+
if (uart->has_peek) {
340+
uart->has_peek = false;
341+
*buffer++ = uart->peek_byte;
342+
size--;
343+
bytes_read = 1;
344+
}
345+
346+
if (size > 0) {
347+
int len = uart_read_bytes(uart->num, buffer, size, pdMS_TO_TICKS(timeout_ms));
348+
if (len < 0) len = 0; // error reading UART
349+
bytes_read += len;
350+
}
351+
352+
353+
UART_MUTEX_UNLOCK();
354+
return bytes_read;
355+
}
356+
329357

330358
uint8_t uartRead(uart_t* uart)
331359
{

cores/esp32/esp32-hal-uart.h

+1
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ void uartGetEventQueue(uart_t* uart, QueueHandle_t *q);
6969

7070
uint32_t uartAvailable(uart_t* uart);
7171
uint32_t uartAvailableForWrite(uart_t* uart);
72+
size_t uartReadBytes(uart_t* uart, uint8_t *buffer, size_t size, uint32_t timeout_ms);
7273
uint8_t uartRead(uart_t* uart);
7374
uint8_t uartPeek(uart_t* uart);
7475

0 commit comments

Comments
 (0)