I'm trying to mix Serial.read() and Serial.readBytes() when reading over one of the Serial ports on my Arduino Due. I thought that using Serial.read() would clear what is on the serial, and then subsequent reads by readBytes() would not pick up what has already been read by the Serial.

The main reason I'm trying this approach is because large Serial reads can be unstable using the Arduino supplied Serial.read() - I've checked the Serial buffer with a logic analyzer, so I know that the data is on the Serial line, but Serial.read() drops some bytes.

Hence why I want to use Serial.readBytes().

Here's what I'm doing:

#define FIXED_LENGTH 10
char * buffer, * bp;
int index, i, bufSize;
    data = Serial3.read();
    Serial.print(data,HEX); //Check the data received

    if(index == FIXED_LENGTH){
       //...code to calculate bufSize from buffer...//
       bp = (char*)calloc(1,bufSize); //calloc bp size
       Serial3.readBytes(bp,bufSize); //read the rest of what's on the serial

I get the correct output from the first part of the code - that is, it correctly calculates bufSize from buffer. But when I try to store the following length into bp, it gives me more or less the first output that I have already read on the first few passes!


Data coming in over Serial3.read() [10]: 0123456789

The next characters in Serial3 are [6]: ABCDEF

Stored into bp using Serial3.readBytes() [6]: 000045

Do I need to flush Serial3 before attempting to read the next set of bytes off of it? Do I need to wait/set a timeout before advancing to the next operation?

  • 1
    You did not initialize buffer: you are going to corrupt your memory. Sep 26, 2016 at 8:31
  • 1
    Sorry but your code is full of bugs, its going to blow up in you face. index needs initialising, you don't check to see if the calloc fails, you don't free the calloc. I would approach it a different way, use readByte into a static buffer of fixed size, process the data, read again. Sep 26, 2016 at 12:31
  • 1
    You're right, this code would be full of bugs, but it's just a snippet as part of a larger portion of code. Please assume that I am properly initializing buffer and setting up the rest of the variables correctly. My question is dealing with readBytes and reading from the Serial line.
    – Andrew
    Sep 26, 2016 at 17:19
  • You should probably check out create a minimal working example to enable people to help you.
    – GMc
    Jun 18, 2019 at 7:00


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.