Skip to content

Commit 16c0f3f

Browse files
committed
Implement HardwareSerial::peek
1 parent 7960b63 commit 16c0f3f

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

cores/esp8266/HardwareSerial.cpp

+15-2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333

3434
HardwareSerial::HardwareSerial(int uart_nr)
3535
: _uart_nr(uart_nr)
36-
, _uart(0)
3736
{}
3837

3938
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
4746
}
4847

4948
_uart = uart_init(_uart_nr, baud, (int) config, (int) mode, tx_pin);
49+
_peek_char = -1;
5050
}
5151

5252
void HardwareSerial::end()
@@ -118,6 +118,9 @@ int HardwareSerial::available(void)
118118
}
119119

120120
int result = static_cast<int>(uart_rx_available(_uart));
121+
if (_peek_char != -1) {
122+
result += 1;
123+
}
121124
if (!result) {
122125
optimistic_yield(USD(_uart_nr) / 128);
123126
}
@@ -126,7 +129,12 @@ int HardwareSerial::available(void)
126129

127130
int HardwareSerial::peek(void)
128131
{
129-
return -1;
132+
if (_peek_char != -1) {
133+
return _peek_char;
134+
}
135+
// this may return -1, but that's okay
136+
_peek_char = uart_read_char(_uart);
137+
return _peek_char;
130138
}
131139

132140
int HardwareSerial::read(void)
@@ -135,6 +143,11 @@ int HardwareSerial::read(void)
135143
return -1;
136144
}
137145

146+
if (_peek_char != -1) {
147+
auto tmp = _peek_char;
148+
_peek_char = -1;
149+
return tmp;
150+
}
138151
return uart_read_char(_uart);
139152
}
140153

cores/esp8266/HardwareSerial.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,8 @@ class HardwareSerial: public Stream
136136

137137
protected:
138138
int _uart_nr;
139-
uart_t* _uart;
139+
uart_t* _uart = nullptr;
140+
int _peek_char = -1;
140141
};
141142

142143
extern HardwareSerial Serial;

cores/esp8266/uart.c

+3
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ int uart_read_char(uart_t* uart)
8080
if(uart == NULL || !uart->rx_enabled) {
8181
return -1;
8282
}
83+
if (!uart_rx_available(uart)) {
84+
return -1;
85+
}
8386
return USF(uart->uart_nr) & 0xff;
8487
}
8588

0 commit comments

Comments
 (0)