In my milling machine control I use a string to recieve the serial transmission then convert it to a character array after an end of transmission char is recieved. The numerical data is sent in hexadecimal ensuring that no valid numerical data gets misinterpreted as an end of transmission.
From the charracter array I have fixed byte positions for the beginning of each field. A user function reads characters then converts the hex char to its hex numerical counterpart and concates the group of chars one at a time into the appropriate byte locations. See below:
My command resembles MA 01FA 2EE7 *
I have up to 55 characters including whitespace allocated. The whitespace is a human reading aide and has no bearing on fetching the field data.
String HexToInt = "0123456789ABCDEFX";
//The 'X' is included so that I can get a return value indicating an ignored field.
int Chex(char symbol)
{
int temp;
temp = HexToInt.indexOf(symbol);
if(temp==16)
{
return -1; //An ignored field
}
else
{
return temp;
}
}
int GetValueFromString(char * buffer, int offset)
{
int temp;
int j;
int Ignored;
for(j=0; j<=3; j++)
{
temp = Chex(buffer[ j + offset])
if(temp==-1)
{
Ignored = -1;
}
}
if(Ignored != -1)
{
temp = Chex(buffer[ offset]) * 4096;
temp = temp + Chex(buffer[1 + offset]) * 256;
temp = temp + Chex(buffer[2 + offset]) * 16;
temp = temp + Chex(buffer[3 + offset]);
return temp;
}
else
{
return '/0';
}
}