This function will terminate if the defined length of characters has been read or if the time out (Serial.setTimeout()). If it returns 0 that means no valid data is available.
Syntax
Following is the syntax of Serial.readBytes() function:
Parameters
buffer: The buffer array to store the received bytes. The allowed data types are char array or byte.
length: This refers to the specific number of bytes that should be retrieved from the serial buffer. The allowed data type is int.
Returns
The number of bytes read from the serial buffer.
Example Code
Following code explains the use of Serial.readBytes() function in Arduino.
char buf[BUFFER_SIZE];
void setup() {
Serial.begin(9600);
Serial.setTimeout(5000); // set the time-out period to 5000 milliseconds (5 seconds)
}
void loop() {
// wait for incoming data
while (Serial.available() == 0) {
// do nothing
}
// read the incoming bytes:
int rlen = Serial.readBytes(buf, BUFFER_SIZE);
// prints the received data
Serial.print("I received: ");
for (int i = 0; i < rlen; i++) {
Serial.print(buf[i]);
}
}
In the above code the setup() function sets the timeout period to 5 seconds using Serial.setTimeout(5000).
In the loop() function, the program enters a while loop that waits for incoming data by checking if Serial.available() is greater than 0. This while loop ensures that the program waits until data is available before attempting to read it, and it will exit as soon as data is received.
Once incoming data is detected, the program reads the bytes using Serial.readBytes() and stores them in the buf array. The received data is then printed to the serial monitor using a for loop that iterates over the buf array.
Output
Here in output, we can see the number of bytes read by the function.
Conclusion
The Serial.readBytes() is a function in Arduino that enables the reading of a specified number of bytes from the serial buffer and saving them into an array buffer. It gives total read bytes, or -1 if no data is available and return 0 if no valid input is there. This function is commonly used in Arduino programs that require communication with external devices over a serial connection.