7

I'm trying to program a little bit in Arduino, but I'm stuck with probably something trivial.

This is what I have:

char ang[3], lat[9];
dtostrf(GPS.angle, 3, 0, ang);
dtostrf(GPS.latitude, 9,5, lat);

Serial.println(lat);             
Serial.println(ang);
Serial.println("-------");

I would expect the following in the serial monitor:

5111.60160
267
-------

But instead, I'm getting this:

5111.60160
2675111.60160
-------

So it looks like the ang holds both the angle and the latitude....

Why is this happening? And how can I solve this?

My goal is to make one big string, comma separated, from the data stored in GPS

3
  • You might need to null-terminate the string. The last byte should be \0
    – sachleen
    Commented Apr 16, 2014 at 16:46
  • Euuh, ok. How do I do that???
    – stUrb
    Commented Apr 16, 2014 at 16:48
  • 1
    Increase the size of the arrays by 1 and then do ang[3] = '\0';
    – sachleen
    Commented Apr 16, 2014 at 16:50

1 Answer 1

4

Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.

The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.

I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

char ang[3+1], lat[10+1];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).

Try increasing just your array sizes first; it'll probably work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.