I would like to receive data from the sensor to my esp32-cam, then save them into SD CARD.
The sensor has two kinds of packet formats.
One of them which is 1500 bytes in length is the target to receive.
It has specific headers and tails.
What kind of data is that? It doesn't look like ASCII. Apart from the header 0x51, 0xaa, that you could discard (but aren't discarding), the image shows values like 0xfe and 0xf2: this is not ASCII either. Maybe it's some kind of extended ASCII?
Can you post an example of how this string is supposed to look like, given a certain input?
Get rid of the .readBytes(), it has a default timeout of 1 second, and it is hard to synchronize with incoming data. If it stops because of a timeout, do you know if the data has a zero-terminator ? I don't.
The gap between the serial data is only small and the Arduino functions are not meant to detect that gap.
Can you tell more about the format ? Does it always start with 0x51, 0xAA and end with 0x0D, 0x0A ? Then you can ignore the gap and detect the begin and end.
const uint16_t RECORD_SIZE = 1500;
boolean started = false;
b = Serial.read();
if (b == 0x51) // Start byte
idx = 0;
started = true;
if (started) // Ignore anything received until we get a start byte.
buffer[idx++] = b;
if (idx > RECORD_SIZE - 1)
// Process the data here
started = false;
Are you shure about that? I've checked, it is.
I have to admit, I've never used timeout with an async communication (it's a non sense from my point of view especcially if you have a "start" and a "stop" bytes).
Anyway, I think it would be a better approach to read byte by byte up to both terminators bytes which is always 0x0D, 0x0A (carriage return, new line), instead of reading a fixed number of bytes.
Yes, in this situation it is better read the bytes one by one and deal with the protocol in the code, such as red_car gave a start in reply #7.
In my opinion this is always better than .readBytes() because of its undocumented behavior. The disadvantage is that you have to use millis() to be able to detect a timeout. With a timeout the code gets larger, see my millis_serial_timeout.ino