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;
while(1)
{
if(Serial3.available())
{
data = Serial3.read();
Serial.print(data,HEX); //Check the data received
buffer[index]=data;
index++;
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
break;
}
}
}
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!
Example:
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?
buffer
: you are going to corrupt your memory.