我正在尝试使用Ubuntu 14.04上的USB GPS设备(UB-353 +)获取GPS数据。它在\dev
目录中的名称是ttyACM0
,通过命令cat ttyACM0
我可以看到NMEA GPS数据,如下图所示。
我不想自己解析NMEA数据,而是希望通过gpsd
守护程序获取纬度和经度,因此我使用
gpsd
和libgps-dev
sudo apt-get install gpsd`
sudo apt-get install libgps-dev
之后,我使用以下代码获取GPS数据:
/*compile command: gcc -o gps get_get.c -lm -lgps*/
#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) {
/* wait for 2 seconds to receive data */
if (gps_waiting (&gps_data, 2000000)) {
/* 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); EDIT: tv.tv_sec isn't actually the timestamp!
printf("latitude: %f, longitude: %f, speed: %f, timestamp: %ld\n", gps_data.fix.latitude, gps_data.fix.longitude, gps_data.fix.speed, gps_data.fix.time); //EDIT: Replaced tv.tv_sec with gps_data.fix.time
} else {
printf("no GPS data available\n");
}
}
}
sleep(3);
}
/* When you are done... */
gps_stream(&gps_data, WATCH_DISABLE, NULL);
gps_close (&gps_data);
return EXIT_SUCCESS;
}
但是,我发现此代码经常(并非总是)卡在gps_waiting (&gps_data, 2000000)
,这意味着函数gps_waiting()
返回0.但我不知道为什么会发生这种情况因为GPS设备正常工作正常。
我已经被这个错误困住了几天,非常感谢你的帮助!
答案 0 :(得分:1)
不确定您对C ++的熟悉程度,但是您想尝试一下:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <libgpsmm.h>
int main(void)
{
gpsmm gps_rec("localhost", DEFAULT_GPSD_PORT);
if (gps_rec.stream(WATCH_ENABLE | WATCH_JSON) == NULL) {
std::cerr << "No GPSD running.\n";
return 1;
}
for (;;) {
struct gps_data_t *newdata;
if (!gps_rec.waiting(50000000)) continue;
if ((newdata = gps_rec.read()) == NULL) {
std::cerr << "Read error.\n";
return 1;
} else {
while (((newdata = gps_rec.read()) == NULL) ||
(newdata->fix.mode < 1)) {
// Do nothing; don't want to output wrong initial time
}
timestamp_t ts = newdata->fix.time;
double latitude = newdata->fix.latitude;
double longitude = newdata->fix.longitude;
// convert GPSD's timestamp_t into time_t
time_t seconds;
seconds = (time_t)ts;
auto tm = *std::localtime(&seconds);
std::ostringstream oss;
oss << std::put_time(&tm, "%d-%m-%Y %H:%M:%S");
auto time_str = oss.str();
// set decimal precision
std::cout.precision(6);
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout << time_str << "," <<
latitude << "," <<
longitude << '\n';
}
}
return 0;
}
并编译:{{1}}
我使用该代码(here的一个要点)作为我使用gpsd的基础,我还没有任何奇怪的问题。如果它是编译器问题,gspd守护程序问题或其他原因,我们可以缩小范围。