Parse GPS String for Time and Coordinates

specific approach

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

#define TIME_LEN 6
#define GPRMC_LEN 7
#define LATI_LEN 8
#define LONGI_LEN 9
#define OFFSET 3
#define SEP_CHAR ','
//GPRMC_LEN includes ,

typedef struct{
    char latitude[LATI_LEN + 1];
    char longitude[LONGI_LEN + 1];
    char direct_ns;
    char direct_ew;
    
} GPS_FIELDS;

void manual_strcpy(const char *src, char *dest){
    while(*src && *src != SEP_CHAR){
        *dest = *src;
        dest++;

        src++;
    }
    *dest = '\0';    //terminate the string
}

void parse_gprmc(char *nmea) {
    char i; 
    char *pntr;
    GPS_FIELDS vals;
    
    if(*nmea == '\0'){
        printf("Invalid");
        return;
    }
    
    manual_strcpy( (nmea+GPRMC_LEN+TIME_LEN+OFFSET), vals.latitude);
    
    vals.direct_ns = *(nmea+GPRMC_LEN+TIME_LEN+OFFSET+LATI_LEN+1);  //exclude comma
    
    manual_strcpy( (nmea+GPRMC_LEN+TIME_LEN+2*OFFSET+LATI_LEN), vals.longitude);
    
    vals.direct_ew = *(nmea+GPRMC_LEN+TIME_LEN+(2*OFFSET)+LATI_LEN+LONGI_LEN+1);
    
    printf("Time: ");
    pntr = nmea+GPRMC_LEN;
    for(i = 0; i<3; i++){
        putchar(*pntr++);
        putchar(*pntr++);
        if(i<2) putchar(':');
        else putchar('\n');
    }
    printf("Latitude: %s %c\n", vals.latitude, vals.direct_ns);
    printf("Longitude: %s %c\n", vals.longitude, vals.direct_ew);
    
}   

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

Solving Approach

 

 

 

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