Hi,
I just get crazzy with a bit of code for calculating a simple XOR checksum on a char array to build a message for a serial stream over an xbee. The message has the same format as NEMA message $..*checksum
The checksum is even wrong calculated. I checked it here: cecksum calculator.
The code on the other side for checkin the checksum works fine with the same algorithm!? Hope you have an idea. I extracted the part to a test program to debug it more easy. Only to avoid confusion:
First I have string to build with the message. Only for the checksum test I transfered it to char array.
String MessageStr ="";
bool read = false;
char MessageBuffer[100]="";
void setup()
{
Serial.begin(9600);
Serial.println("Checksum-Test");
Serial.println("Enter String to check: ");
}
void loop()
{
if (Serial.available())
{
while (Serial.available())
{
MessageStr=Serial.readString();
read = true;
}
if (read)
{
Serial.print("String read: ");
Serial.println(MessageStr);
BuildMessage();
read=false;
Serial.println("Next String: ");
}
}
}
void BuildMessage(void) {
int MesChecksum=0;
char buf[12];
//here i build the message
/*Generating and parsing message checksum
starting at the 2. Position to not calculate initial '
Here is the part that checks the checksum without any problem:
boolean TelegramCheckChecksum (char* Message, int MessageLength)
{
byte checksumReceived=0, checksum=0;
for (int x = 1; x < MessageLength; x++)
{
if (Message[x] == '*') //Checksum starts with '*'
{
checksumReceived = strtol(&Message[x + 1], NULL, 16); //Parsing received checksum... |strtol parsing string to integer
break; //Exit for and continue with next if
}
else
{
checksum ^= Message[x]; //XOR the received data...
}
}
if (checksum==checksumReceived)
{
return true;
}
else
{
return false;
}
}
I hope somebody has an idea where the failure is.
Regards
Andreas*/
MessageStr.toCharArray(MessageBuffer, MessageStr.length());
//for (int x = 1; x < (sizeof(MessageBuffer)/sizeof(MessageBuffer[0])); x++)
//{
//
//if (MessageBuffer[x] == '*')
//{
//Serial.println("Hier ist der break");
//break;
//}
//else
//{
//Serial.print(MessageBuffer[x]);
//MesChecksum ^= MessageBuffer[x]; //XOR the Message data...
//}
//
//Serial.println(x);
//}
int x = 1;
while (MessageBuffer[x]!='*')
{
MesChecksum ^= MessageBuffer[x]; //XOR the Message data...
Serial.print(x); Serial.print(" ");
Serial.print(MessageBuffer[x]); Serial.print(" ");Serial.println(MessageBuffer[x], BIN);
x++;
}
MessageStr += MesChecksum;
Serial.println(MessageStr);
//for clearing the MessageStr:
for (int x = 0; x < (sizeof(MessageBuffer)/sizeof(MessageBuffer[0])); x++)
{
MessageBuffer[x]=0;
}
MesChecksum=0;
}
Here is the part that checks the checksum without any problem:
§DISCOURSE_HOISTED_CODE_1§
I hope somebody has an idea where the failure is.
Regards
Andreas