2

我正在尝试使用 libgps 从 Adafruit 终极 gps 读取数据。我找到了一个代码示例,它提供了我需要的所有信息,除了 gps 时间。如何获取 gps 通过串行端口发送的 gps 时间,最好以小时/分钟/秒为单位?

我试过gps_data.fix.time了,但我不确定这是系统时间还是 GPS 时间。

#include <gps.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>

int main() {
    int rc;
    struct timeval tv;

    struct gps_data_t gps_data;
    if ((rc = gps_open("localhost", "2947", &gps_data)) == -1) {
        printf("code: %d, reason: %s\n", rc, gps_errstr(rc));
        return EXIT_FAILURE;
    }
    gps_stream(&gps_data, WATCH_ENABLE | WATCH_JSON, NULL);

    while (1) {
        /* time to wait to receive data */
        if (gps_waiting (&gps_data, 500000)) {
        /* read data */
        if ((rc = gps_read(&gps_data)) == -1) {
            printf("error occured reading gps data. code: %d, reason: %s\n", rc, gps_errstr(rc));
        } else {
            /* Display data from the GPS receiver. */
            if ((gps_data.status == STATUS_FIX) && 
                (gps_data.fix.mode == MODE_2D || gps_data.fix.mode == MODE_3D) &&
                !isnan(gps_data.fix.latitude) && 
                !isnan(gps_data.fix.longitude)) {
                    gettimeofday(&tv, NULL);
                //*****************WOULD LIKE TO PRINT THE TIME HERE.*****************************
                    printf("height: %f, latitude: %f, longitude: %f, speed: %f, timestamp: %f\n", gps_data.fix.altitude, gps_data.fix.latitude, gps_data.fix.longitude, gps_data.fix.speed, gps_data.fix.time/*tv.tv_sec*/);
            } else {
                printf("no GPS data available\n");
            }
        }
    }

    //sleep(1);
}

/* When you are done... */
gps_stream(&gps_data, WATCH_DISABLE, NULL);
gps_close (&gps_data);

return EXIT_SUCCESS;

}

4

2 回答 2

1

我在 libgps 中跟踪了一些代码,而 gps_data.fix.time 似乎是 struct timespec 类型的变量。其定义如下:

struct timespec
    time_t  tv_sec;
    long    tv_nsec;    
};

您可能想尝试打印gps_data.fix.time.tv_sec和/或gps_data.fix.time.tv_nsec

希望这可以帮助。

于 2020-04-01T20:52:44.903 回答
0

我阅读了我的 PC 的 gps.h 并发现 timesec_t 是双倍的。我尝试如下。

int my_gps_time; // for cast fix.time(double) to int
struct tm *ptm; // for date and time

...
my_gps_time = gps_data.fix.time;
ptm = localtime((time_t *)&my_gps_time);
printf("time: %04d/%02d/%02d,%02d:%02d:%02d\n",\
       ptm->tm_year + 1900, ptm->tm_mon + 1,\
       ptm->tm_mday,ptm->tm_hour, ptm->tm_min, ptm->tm_sec); 
...
于 2020-08-20T07:30:28.860 回答