Serial.readBytes()
Description
Serial.readBytes() reads characters from the serial port into a buffer. The function terminates if the specified length has been read, or it times out (see Serial.setTimeout()).
Serial.readBytes() returns the number of characters placed in the buffer. A 0 means no valid data was found.
Serial.readBytes() inherits from the Stream utility class.
Syntax
Serial.readBytes(buffer, length)
Parameter Values
- 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.
Return Values
- The number of bytes placed in the buffer. Data type: size_t.
Example Code
- Type "HELLO" on Serial Monitor and click Send button:
- The result on Serial Monitor:
※ NOTES AND WARNINGS:
- Serial.readBytes() may read a stream of bytes in multiple times (resulting in multiple fragments). To read a stream of bytes at one time, there are two ways:
- Based on the delimiter: Use Serial.readBytesUntil() with delimiter.
- Based on the fixed length: Wait until the fixed number of bytes is available. for example:
- Make sure that the read length does NOT exceed the buffer size. The below is the best practice:
- 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
- Language : Arduino - Serial
- Language : Serial.available()
- Language : Serial.availableForWrite()
- Language : Serial.begin()
- Language : Serial.end()
- Language : Serial.find()
- Language : Serial.findUntil()
- Language : Serial.flush()
- Language : Serial.getTimeout()
- Language : if(Serial)
- Language : Serial.parseFloat()
- Language : Serial.parseInt()
- Language : Serial.peek()
- Language : Serial.print()
- Language : Serial.println()
- Language : Serial.read()
- Language : Serial.readBytesUntil()
- Language : Serial.readString()
- Language : Serial.readStringUntil()
- Language : serialEvent()
- Language : Serial.setTimeout()
- Language : Serial.write()
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |