mbradley
Joined: 11 Jul 2009 Posts: 118 Location: California, USA
|
NMEA Checksums |
Posted: Sun Jan 17, 2010 5:43 pm |
|
|
I have wrapped a project up, and thought I would share a piece of it for everyone to use.
This is for dealing with the hex checksum in GPS messages. It will allow you to validate the string, as well as generate a checksum if you are outputing messages as well.
Code: |
/*
file: nmea_chk.c
project: open functions
description: NMEA checksum validate and generate
compiler: CCS C
written by : Michael Bradley
2 Functions:
------------------------------------------------------
nmea_validateChecksum(char *strPtr);
pass a string to validate data against checksum
returns either TRUE (1) or FALSE (0)
nmea_generateChecksum(char *strPtr);
pass a complete user generated string that does not contain '*xx'
returns binary byte that is the checksum, you must convert to hex.
simple way to print it out:
int8 chk;
chk = nmea_generateChecksum(origString);
printf("%s*%2X\r\n",origString,chk);
*/
// this takes a nmea gps string, and validates it againts the checksum
// at the end if the string. (requires first byte to be $)
int8 nmea_validateChecksum(char *strPtr)
{
int p;
char c;
unsigned int8 chksum;
unsigned int8 nmeaChk;
int8 flagValid;
char hx[5] = "0x00";
flagValid = TRUE; // we start true, and make it false if things are not right
if (strPtr[0] != '$' ) { flagValid = FALSE; }
// if we are still good, test all bytes
if (flagValid == TRUE)
{
c = strPtr[1]; // get first chr
chksum = c;
p = 2;
while ( ( c != '*' ) && ( p < SERIAL_STR_SIZE ) )
{
c = strPtr[p]; // get next chr
if ( c != '*' ) { chksum = chksum ^ c; }
p++;
}
// at this point we are either at * or at end of string
hx[2] = strPtr[p];
hx[3] = strPtr[p+1];
hx[4] = 0x00;
nmeaChk = atoi(hx);
if ( chksum != nmeaChk ) { flagValid = FALSE; }
}
return flagValid;
}
// this returns a single binary byte that is the checksum
// you must convert it to hex if you are going to print it or send it
unsigned int8 nmea_generateChecksum(char *strPtr)
{
int p;
char c;
unsigned int8 chksum;
c = strPtr[0]; // get first chr
chksum = c;
p = 1;
while ( c != 0x00 )
{
c = strPtr[p]; // get next chr
if ( c != 0x00 ) { chksum = chksum ^ c; }
p++;
}
return chksum;
}
|
_________________ Michael Bradley
www.mculabs.com
Open Drivers and Projects |
|