Arduino / C: Convert byte array to string or other comparable text format

arduinobytearrayc

I am using some third party libraries for some third party hardware. The libraries communicate with the hardware over a serial connection. Using the libraries I send data over the serial interface to the hardware and get a response, which is stored in an array:

// This is the byte array declared in the third party libraries
// that stores data sent back from the external hardware
byte comm_buf[201];

/* I send data to hardware, comm_buf gets filled */

// Printing out the received data via a second serial line to which
// I have a serial monitor to see the data

for (int i = 0; i <= 50; i++) {
  Serial.print(gsm.comm_buf[i]);
}    

// This is printed via the second monitoring serial connection (without spaces)
13 10 43 67 82 69 71 58 32 48 44 51 13 10 13 10 79 75 13 10 00

// It is the decimal ascii codes for the following text
+CREG: 0,3 

How can I convert a byte array into a format that I can evalute in code so I can perform an operation like the following pseudo code;

byte comm_buf[201];

/* I send data to hardware, comm_buf gets filled */

if (comm_buf[] == "CREG: 0,3" ) {
  // do stuff here
}

Do I need to convert it to a string some how, or compare to another char array perhaps?

Best Answer

Here are all functions in string.h for string/memory comparison that you could use with arduino. You could use strcmp or memcmp.

Beware you can't compare in C two strings by simply using == operator. You would just compare values of two memory pointers.

Here is an example of comparison inside your buffer:

if (strcmp((const char*)gsm.comm_buf, "\r\n+CREG: 0,3\r\n\r\nOK\n")==0)
{
    Serial.print("abc");
}

You can use strcmp if your recieved message is null byte terminated, if not you will have to use memcmp for the job.

For both functions You have to check if return value is zero, then those strings are equal.

If you want to compare not from first byte of buffer (with zero index) but for example fifth (index 4) you can just add 4 to your pointer:

if (strcmp((const char*)gsm.comm_buf + 4, "\r\n+CREG: 0,3\r\n\r\nOK\n")==0)
Related Topic