Simvik

Drone GPS: check an NMEA sentence

Verify a GPS sentence's checksum before the navigation code trusts its position. A medium embedded C problem (Arrays and strings), run and graded in the…

medium · Arrays and strings · parsing · checksum · hex · product

Product: Drone GPS receiver (Aerospace and drones)

Requirement. The flight controller navigates from the GPS receiver's NMEA sentences, such as $GPGGA,...*47. A corrupted position could fly the drone into a building, so only sentences whose checksum matches are used.

A valid sentence starts with $, has a *, and after the * exactly two hex digits (upper or lower case), followed by the end of the string or by \r\n. The checksum is the XOR of every character between the $ and the *, not including them.

Return whether s is a valid sentence with a matching checksum.

Starter code

bool nmea_valid(const char *s) {
  const char *star = strchr(s, '*');
  uint8_t x = 0;
  for (const char *p = s; p < star; p++) x ^= (uint8_t)*p;
  int hi = star[1] <= '9' ? star[1] - '0' : star[1] - 'A' + 10;
  int lo = star[2] <= '9' ? star[2] - '0' : star[2] - 'A' + 10;
  return x == hi * 16 + lo;
}

Example tests

A position fix

printf("%d\n", nmea_valid("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"));

Expected output:

1

A damaged digit

printf("%d\n", nmea_valid("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*46"));

Expected output:

0

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems