I am trying to communicate with a usb dongle via serial communication. My communication works, however I cant get the device to correctly parse the communication. My devices reads the message and compares it with a hardcoded c-string. It parses and recognizes that it's the correct string, but when I try to parse the value after the : character, it returns 0x00000000 and I have no idea why. I've tried using char cast and use atoi, I tried using a simple ascii translation, and even doing a bitwise addition operation as shown here: convert subset of vector<uint8_t> to int
For example:
I send "Heart Rate:55"
It parses and recognizes that "Heart Rate:" but when I tell it to go find the 55 and bring it back to do stuff with it, it gives me a 0x00000000
Heres a snippet:
const uint8_t hrmSet[] = "Heart Rate:";
/** Find the : character in the string and break it apart to find if it matches,
and determine the value of the value of the desired heart rate. **/
int parse(uint8_t *input, uint8_t size)
{
for (uint8_t i = 0; i < size; i++)
{
if (input[i] == ':')
{
if (compare_string(input, hrmSet, i) == 0)
{
int val = 0;
for (int j = i+1; j < size; j++)
{
if (!isdigit(input[j]))
{
for (int k = i; k < j; k++)
{
val <<= 8;
val |= input[k];
}
}
}
return val;
}
return -1;
}
}
return -1;
}
Compare string function
/** Compare the input with the const values byte by byte to determine if they are equal.**/
int compare_string(uint8_t *first, const uint8_t *second, int total)
{
for (int i = 0; i < total; i++)
{
if (*first != *second)
{
break;
}
if (*first == '\0' || *second == '\0')
{
break;
}
first++;
second++;
}
if (*first == ':' && *second == ':')
{
return 0;
}
else
{
return -1;
}
}
I check for not isdigit to find the end of the string, again, because I dont know how long it will be every time.
The K loop is there because of this related question: http://stackoverflow.com/questions/17813350/convert-subset-of-vectoruint8-t-to-int?lq=1 – Ronin Oct 22 '14 at 23:15