Michael Divia
Michael Divia

Reputation: 13

Read an incoming HEX packet from Serial

I'm coding a on an arduino and I am communicating with an other device in HEX. I would like to know how to read the data he sends me.

I am sending a HEX packet (everything good here, no problem)

//Ask for Data
Serial.write(askData, sizeof(askData));

After this I will receive data (in HEX). I need to store it all to use it later. The only thing I know is that it will end with a "16". I dont know the length of the packet in advance. Here is an example or packet that I can reveive :

68   4E   4E   68   08   09   72   90   90   85   45   68   50   49   06   19   00   00   00   
0C   14   02   00   00   00   8C   10   12   35   02   00   00   0B   3B   00   00   00   8C   
20   14   02   00   00   00   8C   30   14   00   00   00   00   04   6D   2F   09   61   24   
4C   14   02   00   00   00   42   6C   5F   2C   42   EC   7E   7F   2C   0A   92   2A   00   
10   0A   92   2B   00   10   39   16

Can someone help me please ?

Upvotes: 1

Views: 2115

Answers (1)

Finn
Finn

Reputation: 159

This arduino example slightly modified:

/* reserve 200 bytes for the inputString:
 * assuming a maximum of 200 bytes
 */
uint8_t inputString[200];  // a String to hold incoming data
int countInput = 0;
bool stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(115200);
}

void loop() {
  // print the string when 0x16 arrives:
  if (stringComplete) {
    for (int i=0; i<countInput; i++) {
      Serial.print(inputString[i], HEX);
      Serial.print(" ");
    }
    // clear the string:
    countInput = 0;
    stringComplete = false;
  }
}
/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    inputString[countInput] = (uint8_t)Serial.read();

    // if the incoming character is '0x16', set a flag so the main loop can
    // do something about it:
    if (inputString[countInput] == 0x16) {
      stringComplete = true;
    }
    countInput++;
  }
}

Upvotes: 0

Related Questions