Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 9 of 9

Thread: Float to Sting help

  1. #1
    Junior Member
    Join Date
    May 2013
    Posts
    12

    Float to Sting help

    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!

  2. #2
    Junior Member
    Join Date
    May 2013
    Posts
    12
    "Float to stRing" help, that is.

  3. #3
    Senior Member
    Join Date
    Nov 2012
    Posts
    1,925
    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

  4. #4
    Junior Member
    Join Date
    May 2013
    Posts
    12
    el_supremo, your name says it all. Thanks for your help, Pete. I'm not sure what I was doing wrong....

  5. #5
    Junior Member
    Join Date
    May 2013
    Posts
    12
    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?

  6. #6
    Senior Member
    Join Date
    Nov 2012
    Posts
    1,925
    dtostrf worked for me on Teensy3

    Pete

  7. #7
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    28,461
    A recent version added dtostrf (using sprintf). If that function is missing on Teensy3, please upgrade to Teensyduino 1.15.

  8. #8
    Junior Member
    Join Date
    May 2013
    Posts
    12
    Thanks Paul and Pete. dtostrf now works on the Teensy3. I wish sprintf worked on the Teensy2.

  9. #9
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    28,461
    Quote Originally Posted by ChrisOdom View Post
    I wish sprintf worked on the Teensy2.
    Perhaps try adding this to hardware/teensy/boards.txt

    Code:
    teensy2.build.linkoption1=-Wl,-u,vfprintf
    teensy2.build.linkoption2=-lprintf_flt

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •