Thursday, December 07, 2006

[NMEA checksum in Python]

A GPS receiver uses the NMEA standard to communicate within satellites. Every message it receives, called sentence, has a checksum that ensures its correctness.

Calculating the NMEA sentence checksum is simple, just xor some data (as stated for example in http://www.gpsinformation.org/dale/nmea.htm).

In Python? Is a bunch of code.

[code]

from operator import xor

# NMEA sentence, the checksum is after the '*'
# and it's represented in hex.
s = '$GPGGA,123519,4807.038,N,01131.000,'
s += 'E,1,08,0.9,545.4,M,46.9,M,,*47'

# Converts every character in the substring
# between '$' and the '*' (exclusive)
# in a sequence of integral values.

nmea = map(ord, s[1:s.index('*')])

# Reducing with xor the sequence
checksum = reduce(xor, nmea)

# Optionally converts in hex for printing
print hex(checksum)

[/code]

If you run this simple script you can see 0x47 on your terminal... the sentence is correct.

3 comments:

Chaminda Senavirathna said...

how to read the NMEA data using python and how inslall NMEA module in python envirment

nataluca said...

My first experiment was using the pySerial (http://pyserial.sourceforge.net/) library to attach directly to a bluetooth GPS. After that I parsed the stream by hand. Right now, probably, something like Python GIS (http://pygps.org/) coulde be used... but I don't test this module yet.

njcar said...

Thanks dude: you just saved my bacon! I love people like you who post really useful bits of code that just do one thing correctly!