Take the 2-minute tour ×
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

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

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

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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