NMEA checksum calculation
Asked Answered
R

1

8

I have a problem with calculating the checksum for NMEA sentences. I am using the following java code:

private static String getSum(String in) {
    int checksum = 0;
    if (in.startsWith("$")) {
        in = in.substring(1, in.length());
    }

    int end = in.indexOf('*');
    if (end == -1)
        end = in.length();
    for (int i = 0; i < end; i++) {
        checksum = checksum ^ in.charAt(i);
    }
    String hex = Integer.toHexString(checksum);
    if (hex.length() == 1)
        hex = "0" + hex;
    return hex.toUpperCase();
}

This code is similar to many other examples around the internet and everything works fine until I try a sentence like this..

$PSRF101,-2686700,-4304200,3851624,96000,497260,921,12,3*1C

This sentence is from the NMEA Reference Manual and so I assume the checksum will be correct. But when I calculate it, I get *2F as the checksum and not 1C.

I think this is because of the negative values in the sentence, but I have no clue how to deal with them. Does anybody have a suggestion?

Repudiation answered 4/10, 2012 at 9:58 Comment(2)
The - sign makes no difference: the checksum would still be 2FVacillate
Incorrect, every character contributes. If, however, you remove BOTH of the dashes you are in effect XORing twice... which gets you back where you were. Removing one or the other absolutely does change the result.Loria
A
8

The difference of the assumed and the calculated checksums equals to omitting (or having an extra character '3'); so I'd be tempted to believe in error in the NMEA Reference Manual.

You can try some online NMEA calculator to verify the results.
e.g. http://www.hhhh.org/wiml/proj/nmeaxor.html

Aloe answered 4/10, 2012 at 10:33 Comment(3)
The Sirf Manual also has at least one other erroneous command "$GPMSK,318.0,A,100,M,2,*45", which has an extra commaAloe
So, this could be an error of the manual? Because the "$PSRF104,37.3875111,-121.97232,0,96000,237759,1946,12,1*07" would be erroneous too, I get an "*06" from my code and the online calculator, the manual says "*07". Here are negative values again , so I thought it might be wrong because of them.Repudiation
The error between 06 and 07 is simply 01 in hexadecimal. This would suggest that some (perhaps the last character) should have been 0 instead of 1. Then the checksum would match. The '-' signs do not seem to contribute to the error.Aloe

© 2022 - 2024 — McMap. All rights reserved.