Serial.readBytesUntil()

Description

Serial.readBytesUntil() reads characters from the serial buffer into an array. The function terminates (checks being done in this order) if one of the follwing condition is met:

  • The specified length has been read.
  • The timeout is elapsed (see Serial.setTimeout())
  • The delimiter character is detected (in which case the function returns the characters up to the last character before the supplied delimiter). The delimiter itself is not returned in the buffer.

Serial.readBytesUntil() returns the number of characters read into the buffer. A 0 means that the length parameter ≤ 0, a time out occurred before any other input, or a termination character was found before any other input.

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

Syntax

Serial.readBytesUntil(character, buffer, length)

Parameter Values

  • Serial: serial port object. See the list of available serial ports for each board on the Serial main page.
  • character: the character to search for. Allowed data types: char.
  • 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.

Return Values

  • Data type: size_t.

Example Code

const int BUFFER_SIZE = 100; char buf[BUFFER_SIZE]; void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps } void loop() { // check if data is available if (Serial.available() > 0) { // read the incoming bytes: int rlen = Serial.readBytesUntil('\n', buf, BUFFER_SIZE); // prints the received data Serial.print("I received: "); for(int i = 0; i < rlen; i++) Serial.print(buf[i]); } }
  • Select Newline at the ending selection of Serial Monitor
  • Type "HELLO" on Serial Monitor
  • Click Send button:
COM6
Send
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • The result on Serial Monitor:
COM6
Send
I received: HELLO
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ NOTES AND WARNINGS:

  • The delimiter character is discarded from the serial buffer, unless the number of characters read and copied into the buffer equals length.
  • Serial functions are not only used for the communication between an Arduino board and Serial Monitor of Arduino IDE but also used for the communication between:
  • An Arduino board and other Arduino board
  • An Arduino board and other sensors/devices
  • An Arduino board and computer (any Serial software on computer)

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES