Arduino Mega and sending data via serial3.print()

arduinoserial

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);

Best Answer

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));