1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-04-19 23:22:16 +03:00

Implement HardwareSerial::peek

This commit is contained in:
Ivan Grokhotkov 2016-01-25 12:05:02 +03:00
parent 7960b63357
commit 16c0f3f1d5
3 changed files with 20 additions and 3 deletions

View File

@ -33,7 +33,6 @@
HardwareSerial::HardwareSerial(int uart_nr) HardwareSerial::HardwareSerial(int uart_nr)
: _uart_nr(uart_nr) : _uart_nr(uart_nr)
, _uart(0)
{} {}
void HardwareSerial::begin(unsigned long baud, SerialConfig config, SerialMode mode, uint8_t tx_pin) 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); _uart = uart_init(_uart_nr, baud, (int) config, (int) mode, tx_pin);
_peek_char = -1;
} }
void HardwareSerial::end() void HardwareSerial::end()
@ -118,6 +118,9 @@ int HardwareSerial::available(void)
} }
int result = static_cast<int>(uart_rx_available(_uart)); int result = static_cast<int>(uart_rx_available(_uart));
if (_peek_char != -1) {
result += 1;
}
if (!result) { if (!result) {
optimistic_yield(USD(_uart_nr) / 128); optimistic_yield(USD(_uart_nr) / 128);
} }
@ -126,7 +129,12 @@ int HardwareSerial::available(void)
int HardwareSerial::peek(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) int HardwareSerial::read(void)
@ -135,6 +143,11 @@ int HardwareSerial::read(void)
return -1; return -1;
} }
if (_peek_char != -1) {
auto tmp = _peek_char;
_peek_char = -1;
return tmp;
}
return uart_read_char(_uart); return uart_read_char(_uart);
} }

View File

@ -136,7 +136,8 @@ public:
protected: protected:
int _uart_nr; int _uart_nr;
uart_t* _uart; uart_t* _uart = nullptr;
int _peek_char = -1;
}; };
extern HardwareSerial Serial; extern HardwareSerial Serial;

View File

@ -80,6 +80,9 @@ int uart_read_char(uart_t* uart)
if(uart == NULL || !uart->rx_enabled) { if(uart == NULL || !uart->rx_enabled) {
return -1; return -1;
} }
if (!uart_rx_available(uart)) {
return -1;
}
return USF(uart->uart_nr) & 0xff; return USF(uart->uart_nr) & 0xff;
} }