0

I have a GPS antenna attached to a Raspberry Pi and tried to get its coordinates through C++ with the gps.h library. In there, the latitude is defined as double. Now, when I tried to print it out using printf, with %d the output is 5 and with %f it's 0.000000. I'm just tying to get the exact number that's behind the latitude.

I live in Switzerland and the latitude here is at around 47 degrees. I think that the latitude is stored as 4.7... and there could be some rounding happening, hence the output 5.

Thanks to everybody

edit:

struct gps_data_t gps_d;
printf("%d\n", gps_d.fix.latitude);
  • 3
    Please share the relevant code snippet – Odysseus Aug 19 '20 at 08:25
  • 1
    If you are using C++ why are you using printf ? Try to `std::cout << alt << std::endl` – sshmaxime Aug 19 '20 at 08:26
  • 5
    Printing a `double` with %d is undefined behaviour, the displayed value is rubbish. If you print it with %f and the output is 0.00000, then your variable actually contains 0.0 and you have a problem elsewhere. – Jabberwocky Aug 19 '20 at 08:27
  • 1
    @Quallentino It seems you just declared a variable without reading any values from your GPS module before printing latitude – Odysseus Aug 19 '20 at 08:35
  • Are you sure you _actually_ read from the GPS? The code you posted suggests you don't. Please post the relevant lines of your _actual_ code. Is `gps_d` a local or a global variable? – Jabberwocky Aug 19 '20 at 09:01
  • [This SO question](https://stackoverflow.com/questions/32000328/libgps-c-code-example) may be helpful too. – Jabberwocky Aug 19 '20 at 09:02

2 Answers2

1

I see that gps_d.fix.latitude is a double value, you have to use either %f or %lf to print it using printf. And it also says valid if mode is >=2 so check your code if this is the case. If %f is printing 0.0 then probably the variable value contains actually 0.0.

double latitude;    /* Latitude in degrees (valid if mode >= 2) */

However, if you are programming in C++ then you can also print as below:

std::cout << gps_d.fix.latitude << std::endl;
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Nandish
  • 1,136
  • 9
  • 16
0

I agree with Jabberwocky. You can try to read the NMEA to check whether the GPS works.

cat /dev/<GPS Serial Port>
nvu
  • 137
  • 1
  • 7