Playing with Arduino
A page to record my playing with Arduino
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 1.8.13

Last Update

June 19, 2020

inserted by FC2 system