Serial.readBytes(inbuf, --> OFFSET < --, len) -- possible?

No, I am not a C programmer. So let me ask this question:

I have a buffer

char inbuf[512];
int  inbufLen = 512;
int  inbufFill = 0;

I want to read len bytes from Serial into inbuf, but with an offset of inbufFill. Serial does not offer a method

   Serial.readBytes(inbuf, inbufFill, len);

But maybe I can do something like this:?

   char virtbuf[1];
    *virtbuf = &inbuf[inbufFill];
    Serial.readBytes(virtbuf, len);

Of course these 3 lines a wrong, but they hopefully give you a hint what I want to do.

You are missing one key piece of information - how many bytes are there in total?

There is a big difference between the situation where all the bytes will fit in your buffer and the situation where there are too many bytes - for example if you are trying to pick 512 bytes from within 2000 bytes (or even from within 560 bytes).

The Serial.readBytes() is a blocking function. Have a look at the examples in Serial Input Basics - simple, reliable and non-blocking.

However all those examples assume you have space to receive all the data. If you do, then it seems to me easiest to receive it all and then pick out the part you want.

If you don't have room for all the data you will need some means to know when the data starts and then read and discard bytes one by one until you get to the place from which you want to start saving. It should not be too difficult to adapt my code to do that. You need to keep in mind that the Serial input buffer can only hold 64 bytes - but if you take data from it faster than it arrives that will not be an issue.


char* virtbuf = &inbuf[inbufFill];
    Serial.readBytes(virtbuf, len);

Or use pointer math:

Serial.readBytes(inbuf + inbufFill, len);

Thanks Delta_G! So I was quite close to it :-)

@Robin2 Yes,of course. This code part starts with

    //check UART for data
    size_t len = Serial.available();
    if(len > 0){
      if (len+inbufFill > maxRead) len = maxRead - inbufFill;

So I can be sure that there is such amount of data, and it will not block. But thanks for pointing out anyway!

I want to read len bytes from Serial into inbuf, but with an offset of inbufFill. Serial does not offer a method

Note that readBytes does not guarantee it will read len bytes. It might timeout (default is 1 sec) and will block your program for that 1 sec if you are missing a char... So you are better of controlling yourself the incoming data and store them where you want them to go.