[SOLVED] Low performance using readBytes()

Hello,

I'm using the function readBytes() as follows:

void loop() {
  if(Serial.available()>0)
  {
    bytesRead = Serial.readBytes(buffer,10);
    buffer[bytesRead] = '\0';
    strg = buffer;
    
    if(strg.substring(0,1) == "r")  Serial.println("OK");
}

I'm having low performance with this (it takes 1 second to print "OK"). However, if I change the length to 1 (Serial.readBytes(buffer,1)) it prints "OK" immediately. I really need high performance and the length is 10. What could I do?

The readBytes() function is being asked to read up to 10 bytes. So, if there are 20 in the buffer, it will return right away with 10 bytes. If, instead, there are 3 bytes, the function is going to wait for time to expire or 7 more bytes to arrive.

What is sending the data? Do you have any control over the sender?

There are other methods you could use, like readBytesUntil(), that would block only until some specific character arrived.

Or, you could read the data, and store it in an array, and deal with the contents of the array (NOT the String).

Using substring() to extract, and then discard, a String is a waste. There is a [] operator which will give you the specific character at some position, without the overhead of constructing and destructing a String. Or two of them in that snippet.

I really need high performance

But I'm willing to piss away time using Strings...

Loot at how the Arduino reads data in this demo without any blocking code.

...R

How about not doing any processing until 10 bytes are available?

if(Serial.available()> 9) // are at least 10 bytes available?
{

Why are you reading 10 bytes, but only checking the first one? Is this some test for a more sophisticated code to follow?

If you read 10 bytes and then assign a value to buffer[10], then you might have made an error. How large is buffer[] ?

The code you have shown there, does not require any useful feature of the String class.

If all you want to do, is check whether the first character that you got is an 'r', then

if ( buffer[0] == 'r' )
{     
     // you got an r,  do something
}