Parse GPS String for Time and Coordinates

Code

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

void parse_gprmc(char *nmea) {
    char time[7], lat[11], ns, lon[12], ew;
    uint8_t field = 0, i = 0, j = 0;

    while (nmea[i]) {
        if (nmea[i] == ',') {
            field++;
            i++;
            j = 0;
            continue;
        }

        if (field == 1 && j < 6) time[j++] = nmea[i];
        else if (field == 3 && j < 10) lat[j++] = nmea[i];
        else if (field == 4 && j == 0) ns = nmea[i];
        else if (field == 5 && j < 11) lon[j++] = nmea[i];
        else if (field == 6 && j == 0) ew = nmea[i];

        i++;
    }

    time[6] = '\0';
    lat[10] = '\0';
    lon[11] = '\0';

    printf("Time: %.2s:%.2s:%.2s\n", time, time + 2, time + 4);
    printf("Latitude: %s %c\n", lat, ns);
    printf("Longitude: %s %c\n", lon, ew);
}

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

Solving Approach

  1. Initialize variables:
    1. field = 0 to track which comma-separated field we’re in
    2. Buffers for time[7], lat[11], lon[12], and chars for NS, EW

Index variables: i for input string, j for copying characters

2. Loop through the input string:

For each character:

  1. If it’s a comma ,, increment field, reset j = 0, and continue
  2. Else, based on field value:
  3. field == 1: copy 6 characters into time[]
  4. field == 3: copy up to 10 characters into lat[]
  5. field == 4: store 1 character into NS
  6. field == 5: copy up to 11 characters into lon[]
  7. field == 6: store 1 character into EW

    3.Terminate strings:

    1. Add '\0' at the end of time, lat, and lon buffers

      4.Format and print:

  8. Convert time from HHMMSS to HH:MM:SS
  9. Print Latitude: 
  10. Print Longitude: 

     

 

Upvote
Downvote
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