I have this code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define GPS_RX_PIN 2
#define GPS_TX_PIN 3
TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);
void setup()
{
Serial.begin(9600);
ss.begin(4800);
}
char clat[11];
char clng[11];
void loop()
{
bool isGpsLocationValid = false;
do
{
while (ss.available()>0)
{
char c = byte(ss.read());
if (gps.encode(c))
{
if (gps.location.isValid())
{
dtostrf(gps.location.lat(), 11, 6, clat);
dtostrf(gps.location.lng(), 11, 6, clng);
isGpsLocationValid = true;
}
}
}
} while (isGpsLocationValid == false);
Serial.write(clat);
Serial.println();
Serial.write(clng);
}
Now when all is done, the clng value is printed twice in the serial monitor. The value i get is in this format:
27.275869 15.151013
15.151013
As you can see, clng is printed twice. Any ideas why is that?
asked Jun 20, 2014 at 11:56
-
2I think your question may already be answered here: arduino.stackexchange.com/questions/1197/…Peter Bloomfield– Peter Bloomfield2014年06月20日 12:05:47 +00:00Commented Jun 20, 2014 at 12:05
1 Answer 1
The width parameter to dtostrf()
is the width of the resulting string NOT including the null terminator. So you are overflowing the array.
Change:
char clat[11];
char clng[11];
to
char clat[12];
char clng[12];
and it should work.
answered Jun 20, 2014 at 17:03
-
bear in mind, my number is this : 27.275869 . and i have declared 11 digits. i think they are more than enough. i will provide more feedback on this tomorrowuser1584421– user15844212014年06月20日 17:21:37 +00:00Commented Jun 20, 2014 at 17:21
-
2
-
2 digits + 1 sign + 1 dot + 6 decimal digits + 1 NULL = 11. Why do i need to declare more?user1584421– user15844212014年06月21日 01:40:27 +00:00Commented Jun 21, 2014 at 1:40
-
Because
dtostrf
will pad the result string with spaces so that it is at least 11 characters long, so you need 12 chars in your variable. Instead of arguing, you should just do it and see that it works with 12.jfpoilpret– jfpoilpret2014年06月21日 06:46:56 +00:00Commented Jun 21, 2014 at 6:46 -
I did with up to 14 digits and the results remain the sameuser1584421– user15844212014年06月21日 17:56:41 +00:00Commented Jun 21, 2014 at 17:56