print frame from serial between STX and ETX

Hi all,

I would like to collect and print correctly information received from a serial device. I have an Arduino Mega, then, I've connected the TX/RX pins to the serial device (only one TX and one RX) using the Serial2.

I'm sending the following frame to the serial device

uint8_t STX = 2, ETX = 3, DLE = 16;
uint8_t sendByte[8];

void setup() {  
  Serial.begin (9600);
  Serial2.begin (9600);
}

void loop() {
sendByte[0] = (uint8_t)ETX;
    sendByte[1] = (uint8_t)STX;
    sendByte[2] = (uint8_t)1; //sendByte[2]= (uint8_t)1; // Length
    sendByte[3] = (uint8_t)DLE;
    sendByte[4] = (uint8_t)5; //sendByte[4]= (uint8_t)5; // Data (command)
    sendByte[5] = (uint8_t)(256 - 5); // Checksum
    sendByte[6] = (uint8_t)ETX;
    sendByte[7] = (uint8_t)ETX;  
    Serial2.write(sendByte, sizeof(sendByte));
}

The received frame should be: STX, Length, Data, Checksum, ETX.

I should receive different type of data and length "Char" (e.g. 'D') and integer (e.g. 8 or 400).

Using the following code, I receive (sometimes) a value each 16 bytes (I count it).

//  uint8_t dat;
   while(Serial2.available() > 0)
   {
    dat=Serial2.read();
   Serial.print("Received data of size: ");Serial.print(sizeof(dat));Serial.print(" With value: 
   }

I've received the values 8, 255, 3 and plenty of 0s.

Why I'm receiving different values at the same byte? Is it because the speed of the Serial? Because I'm printing different type of data?

I've tried to use the Example 3 from this site "Serial Input Basics - updated - Introductory Tutorials - Arduino Forum" but I'm not printing anything at the Serial Monitor. The original code is from C which uses the type int8 (but I want to convert this code to Arduino).

My goal is to receive all the information in a buffer with mixed data. Is it possible?

Thanks

are you porting this code from another device ?
are you sure you have the Tx and Rx lines connected correctly?
I tend to use Serial1 on the Mega
pin 18 is the serial transmit from the arduino, i.e. Serial1.print()
pin 19 is the serial receive, i.e. Serial1.read()

try printing the received data in hexadecimal

Serial.print(dat, HEX)

Should I use the Serial1 before Serial2?

Now it works, but I don't know how to get and process the data part from the rest of field ETX. Length, Checkcsum and STX.

I just use Serial1 before Serial2 - it is not critical
can you give a hex printout of the received frame?
have a look at serial input basics

Read Serial Input Basics; example three is tailored to your needs; just replace the start- and the endmarker with the STX and ETX.

Parsing is usually simple but we don't know what you exactly receive and what you exactly want to come out. If you give some typical examples, we can look at it and provide suggestions.

Based on your original code, why do you first send an ETX?

More here