89. Parse GPS String for Time and Coordinates


#include <stdio.h>
#include <string.h>

// Parse simplified GPRMC sentence
void parse_gprmc(char *nmea) {
    char *fields[7];
    int index = 0;

    // Tokenize by comma
    char *token = strtok(nmea, ",");
    while (token != NULL && index < 7) {
        fields[index++] = token;
        token = strtok(NULL, ",");
    }

    // Extract time
    char *t = fields[1];
    printf("Time: %.2s:%.2s:%.2s\n", t, t+2, t+4);

    // Latitude
    printf("Latitude: %s %s\n", fields[3], fields[4]);

    // Longitude
    printf("Longitude: %s %s", fields[5], fields[6]);
}

int main() {
    char nmea[100];
    fgets(nmea, sizeof(nmea), stdin);
    parse_gprmc(nmea);
    return 0;
}

NMEA defines how GPS data is transmitted over serial/UART as plain ASCII strings, where each line is called a sentence.

Each sentence starts with $, followed by a 5-character identifier (e.g., GPGGA, GPRMC) and a comma-separated list of data fields.

Example: $GPRMC 

$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A

This sentence means:

FieldMeaning
$GPRMCSentence type: Recommended minimum GPS data
123519Time: 12:35:19 UTC
AStatus: A = Active, V = Void
4807.038,NLatitude: 48°07.038’ N
01131.000,ELongitude: 11°31.000’ E
022.4Speed over ground (knots)
084.4Track angle in degrees
230394Date: 23rd March 1994
003.1,WMagnetic variation
*6AChecksum (XOR of characters after $ and before *)

Why it matters in firmware?

  • Real GPS modules output NMEA strings continuously
  • You often need to extract location/time info via UART
  • Efficient parsing is needed in low-resource environments
     
Loading...

Input

$GPRMC,123519,A,4807.038,N,01131.000,E

Expected Output

Time: 12:35:19 Latitude: 4807.038 N Longitude: 01131.000 E