diff --git a/cores/esp8266/HardwareSerial.cpp b/cores/esp8266/HardwareSerial.cpp index 3e9b8e539..f15782607 100644 --- a/cores/esp8266/HardwareSerial.cpp +++ b/cores/esp8266/HardwareSerial.cpp @@ -33,7 +33,6 @@ HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr) - , _uart(0) {} void HardwareSerial::begin(unsigned long baud, SerialConfig config, SerialMode mode, uint8_t tx_pin) @@ -47,6 +46,7 @@ void HardwareSerial::begin(unsigned long baud, SerialConfig config, SerialMode m } _uart = uart_init(_uart_nr, baud, (int) config, (int) mode, tx_pin); + _peek_char = -1; } void HardwareSerial::end() @@ -118,6 +118,9 @@ int HardwareSerial::available(void) } int result = static_cast(uart_rx_available(_uart)); + if (_peek_char != -1) { + result += 1; + } if (!result) { optimistic_yield(USD(_uart_nr) / 128); } @@ -126,7 +129,12 @@ int HardwareSerial::available(void) int HardwareSerial::peek(void) { - return -1; + if (_peek_char != -1) { + return _peek_char; + } + // this may return -1, but that's okay + _peek_char = uart_read_char(_uart); + return _peek_char; } int HardwareSerial::read(void) @@ -135,6 +143,11 @@ int HardwareSerial::read(void) return -1; } + if (_peek_char != -1) { + auto tmp = _peek_char; + _peek_char = -1; + return tmp; + } return uart_read_char(_uart); } diff --git a/cores/esp8266/HardwareSerial.h b/cores/esp8266/HardwareSerial.h index 51ce09b2a..bf3dc68cb 100644 --- a/cores/esp8266/HardwareSerial.h +++ b/cores/esp8266/HardwareSerial.h @@ -136,7 +136,8 @@ public: protected: int _uart_nr; - uart_t* _uart; + uart_t* _uart = nullptr; + int _peek_char = -1; }; extern HardwareSerial Serial; diff --git a/cores/esp8266/uart.c b/cores/esp8266/uart.c index d7a364008..f2db9ae42 100644 --- a/cores/esp8266/uart.c +++ b/cores/esp8266/uart.c @@ -80,6 +80,9 @@ int uart_read_char(uart_t* uart) if(uart == NULL || !uart->rx_enabled) { return -1; } + if (!uart_rx_available(uart)) { + return -1; + } return USF(uart->uart_nr) & 0xff; }