Description

Serial.readBytes() reads characters from the serial port into a buffer. The function terminates if the determined length has been read, or it times out (see Serial.setTimeout()).

Serial.readBytes() inherits from the Stream utility class.

Syntax

Use the following function to read characters from the serial port and store them in a buffer:

Serial.readBytes(buffer, length)

Parameters

The function admits the following objects and parameters:

  • Serial: serial port object. See the list of available serial ports for each board on the Serial main page.

  • buffer: the buffer to store the bytes in. Allowed data types: array of char or byte.

  • length: the number of bytes to read. Allowed data types: int.

Returns

The number of bytes placed in the buffer. A value of 0 indicates that no valid data was found. Data type: size_t.

Example Code

The following code creates a 5-position buffer and stores the incoming serial characters in it.

char data[6];  // 5 bytes + null terminator

void setup() {
  Serial.begin(9600);
  while (!Serial);

  Serial.println("Send 5 characters:");
}

void loop() {
  if (Serial.available() >= 5) {
    int bytesRead = Serial.readBytes(data, 5);
    data[bytesRead] = '\0';  // Null-terminate the string

    Serial.print("Received: ");
    Serial.println(data);
  }
}

See also