Float to Sting help

Status
Not open for further replies.

ChrisOdom

Member
I have switched from a Teensy2 to a Teensy3 and now much of my code won't work. I've worked around most of the issues (using "while(!Serial){}", for example, after baud rate is established) but I am stuck on converting floats to strings for simple string concatenation. I was using dtostrf, but this doesn't work on the 3.0. I see that some suggest using sprintf, but I've not been able to make that work.

I would appreciate seeing a *simple* FULL code example to take the number 12.345 and have the message "number = 12.345" appear on the serial monitor.

Any assistance would be greatly appreciated. Thanks in advance!
 
Code:
float a = 12.345;

void setup(void)
{
  delay(1000);
  Serial.begin(9600);
  while(!Serial);
  Serial.print("number = ");
  Serial.println(a,3);
  
  char s[20];
  sprintf(s,"number = %6.3f",a);
  Serial.println(s);
}

void loop(void)
{
}
Pete
 
So after a bit more experimentation, I find that sprintf works fine on my Teensy3, but not on my Teensy2 or on my Arduino Uno. Is this to be expected? I'm not sure I understand what's going on under the hood.

I need code that works with all these boards; am I relegated to working only with print and println functions then?
 
A recent version added dtostrf (using sprintf). If that function is missing on Teensy3, please upgrade to Teensyduino 1.15.
 
Status
Not open for further replies.
Back
Top