HardwareSerial::peek()

Abstract

The Serial.peek()/HardwareSerial::peek() reads data from receive buffer without modifying the buffer.

Souce Code

The HardwareSerial::peek() is defined in hardware/arduino/avr/cores/arduino/HardwareSerial.cpp as below.

1
2
3
4
5
6
7
8
int HardwareSerial::peek(void)
{
  if (_rx_buffer_head == _rx_buffer_tail) {
    return -1;
  } else {
    return _rx_buffer[_rx_buffer_tail];
  }
}

No inputs, output is int.

1
2
int HardwareSerial::peek(void)
{

If the head and tail of the buffer is same, there is no data in the buffer, returns -1.

3
4
5
6
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer_head == _rx_buffer_tail) {
  return -1;
} else {

If the head and tail of the buffer is not same, return the oldest data which is stored in buffer[tail].

5
6
7
8
  } else {
    return _rx_buffer[_rx_buffer_tail];
  }
}

This function dose not modify the receive buffer itself.

Version

Arduino AVR Boards 1.8.6

Last Update

August 25, 2019

inserted by FC2 system