Skip to content

Commit

Permalink
Implement HardwareSerial::peek
Browse files Browse the repository at this point in the history
  • Loading branch information
igrr committed Jan 26, 2016
1 parent 7960b63 commit 16c0f3f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
17 changes: 15 additions & 2 deletions cores/esp8266/HardwareSerial.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand Down Expand Up @@ -118,6 +118,9 @@ int HardwareSerial::available(void)
}

int result = static_cast<int>(uart_rx_available(_uart));
if (_peek_char != -1) {
result += 1;
}
if (!result) {
optimistic_yield(USD(_uart_nr) / 128);
}
Expand All @@ -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)
Expand All @@ -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);
}

Expand Down
3 changes: 2 additions & 1 deletion cores/esp8266/HardwareSerial.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ class HardwareSerial: public Stream

protected:
int _uart_nr;
uart_t* _uart;
uart_t* _uart = nullptr;
int _peek_char = -1;
};

extern HardwareSerial Serial;
Expand Down
3 changes: 3 additions & 0 deletions cores/esp8266/uart.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down

0 comments on commit 16c0f3f

Please sign in to comment.