# Arduino Mega and sending data via serial3.print()

So far I have:

float temp = 22.45;
Serial3.print(temp + "\r");


I knew that code would not work from the getgo.
I am attempting to concatenate the temp variable and a carriage return. The board that I will be communicating with will only accept a carriage return at the end and not a new line, otherwise I would have used a println(). How do I combine the float value and a carriage return and send it via Serial3?

EDIT

char tempAr[10];
String tempAsString;
String serialData;

dtostrf(temp,1,2,tempAr);
tempAsString = String(tempAr);

serialData = tempAsString + "\r";
Serial3.print(serialData);


The above code seems to work; however, it is still rough around the edges and I will have to change the width and precision values in the dtostrf per decimal place(ones, tens, hundreds);

• Couldn't you send one after the other? Something like: Serial3.print(temp); Serial3.print('\r'); – bjthom May 24 '12 at 17:52
• I tried that approach, but I did not get a response. – dottedquad May 25 '12 at 0:33
• You might want to take a look at the update in my answer for a more convenient and efficient function – nijansen May 25 '12 at 12:28

The comment by bjthom seems very straightforward, but if that is not an option for you, how about sprintf?

float const val = 22.45;
char buf[64];
sprintf(buf, "%f\r", val);
Serial3.print(buf);


Update

You are right, sprintf is a potential bottleneck. Here is a far more efficient function that gets you around the usage of the String class:

char * ftoa_wr(float f, char * a, int precision=2)
{
char * const ret = a;
long const bp = (long)f;
itoa(bp, a, 10);
while(*a != '\0') a++;
*a++ = '.';
long const ap = abs(
(long)(
(f - bp) * pow(10, precision)
)
);
itoa(ap, a, 10);
while(*a != '\0') a++;
*a++ = '\r';
return ret;
}


With it you could do

char buf[10];
Serial3.print(ftoa_wr(22.45, buf));

• I remember using this trick +1 – jippie May 24 '12 at 19:25
• After researching sprintf some more, I found out sprintf does not work efficiently. I edited my original post with an approach that seems to be working. – dottedquad May 25 '12 at 0:34