Pages: [1] 2 3   Go Down
Author Topic: Concatenate Float w/ a String  (Read 4514 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 16
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Been tinkering with this for a while and just about scratching my head at why it's been so difficult.

I am using the Adafruit library to pull sensor data from 2 DHT11's the values returned are float vars
https://github.com/adafruit/DHT-sensor-library

I'm then trying to post them to a remote server using an Ethernet shield with a ENC28J60 chip
using the EtherCard library
https://github.com/jcw/ethercard

did some homework and tinkered with this on and off for a couple weeks, most of the common C methods aren't available and I've yet to find a workable reference

I have a sample of my code as it stands posted at
https://gist.github.com/4700415

line 132 makes the GET call (commented out)
lines 121 and after are attempts to concatenate the values, I know this is an easy fix for someone with experience so I'm reaching out for a snippet or reference

thanks
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I had some trouble with floats and strings but I got it working. Nick Gammon pointed out that there are some issues with the current string library, it may not be your immediate issue but its worth noteing .
check this out maybe it will help. http://arduino.cc/forum/index.php/topic,146586.0.html

if you look in my code I put a few floats into Strings just after the loop()
Logged

California
Offline Offline
Faraday Member
**
Karma: 91
Posts: 3426
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Multiply it by 10^n where n is the number of digits after the decimal point.
Assign the resulting value to an int or long depending on the size of n.
Do something like this to actually stuff it into the string:
Code:
sprintf(buffer,"MyFloat: %d.%d", myInt/n, myInt%n);
Where myInt is the result from the previous step and n is the number of digits of precision.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 16
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you Arch -- seems to have done the trick

have to see about cleaning up my hacky code and pushing it to github
Logged

Asnieres sur Seine - France
Offline Offline
Jr. Member
**
Karma: 0
Posts: 53
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I was having similar problems with sprintf and floats (http://arduino.cc/forum/index.php/topic,148024.msg1112201.html#msg1112201). I was unaware of the problems with floats, sprintf and Arduino.

Arrch certainly pointed me in the right direction and I wrote a function using his principles. It works fine and does just what I want it to do THANK YOU ARRCH!

However I now have a different bug... for some reason I can't pass the integer value of the number of decimal places I want to display. Have a look at the code below. You'll notice that if I pass the number of decimal places as an argument to the function (FtoChar) I lose 0.01 in the values. But if I hard code the decimal places inside the function (FtoChar2) it works fine.

After a bit of debugging I found out where the problem is and I'm almost more confused. If you uncomment my DEBUG lines you'll notice that I get different results from what should a simple calculation of 10 to the power of 2. If I set iDigs to the value of 2 within the function I get 100 (as I should). If I pass iDigs as an argument, with the integer value of 2, to the function then 10 to the power of iDigs becomes 99 instead of 100 thereby screwing up my actual values.

Code:
//////////////////////////////////////////////////////
//
// FtoChar
//
// Float to char
//
// fVal  Float value to be converted
// iDigs Number of decimal places
// cF    Char var to be modified
//
char* FtoChar(float fVal, int iDigs, char* cF) {

    // Separator = 10 ˆ Number of decimal places
    long dSep = pow(10, iDigs);

// DEBUG
// Serial.print(F("FtoChar dSep: "));
// Serial.println(dSep);

    // Display value = floal value * separator
    signed long slVal = fVal * dSep;

    sprintf(cF, "%d.%d", int(slVal / dSep), int(slVal % int(dSep)));
}

//////////////////////////////////////////////////////
//
// FtoChar2
//
// Float to char (forced 2 decimal places)
//
// fVal  Float value to be converted
// iDigs Number of decimal places
// cF    Char var to be modified
//
char* FtoChar2(float fVal, char* cF) {

  // Force number of decimal places to full 2
  int iDigs = 2;

  // Separator = 10 ˆ Number of decimal places
  long dSep = pow(10, iDigs);
// DEBUG
// Serial.print(F("FtoChar2 dSep: "));
// Serial.println(dSep);
   
  // Display value = floal value * separator
  signed long slVal = fVal * dSep;

  sprintf(cF, "%d.%d", int(slVal / dSep), int(slVal % int(dSep)));
}

void setup() {
  float fTemp = 18.90; // Temperature (Celsius)
  float fHum = 34.80;  // Humidity (percentage)
 
  char cMsg[254], cTemp[8], cHum[8];
 
  // Init serial monitor
  Serial.begin(9600);
  delay(1000);
 
  Serial.print(F("Temp : "));
  Serial.println(fTemp);
  Serial.print(F("Humidity : "));
  Serial.println(fHum);
  Serial.println();

  // Should output Temp: 18.90C - Humidity: 34.80%
  // But it ouputs Temp: 18.89C - Humidity: 34.79%
  FtoChar(fTemp, 2, cTemp);
  FtoChar(fHum, 2, cHum);
  sprintf(cMsg, "Temp: %sC - Humidity: %s%%.", cTemp, cHum);
  Serial.println();
  Serial.println(F("FtoChar:"));
  Serial.println(cMsg);
  Serial.println();
 
  // Correctly outputs Temp: 18.90C - Humidity: 34.80%
  FtoChar2(fTemp, cTemp);
  FtoChar2(fHum, cHum);
  sprintf(cMsg, "Temp: %sC - Humidity: %s%%.", cTemp, cHum);
  Serial.println();
  Serial.println(F("FtoChar2:"));
  Serial.println(cMsg);
 
}

void loop() {
}
Logged

Seattle, WA USA
Online Online
Brattain Member
*****
Karma: 631
Posts: 50041
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Why is FtoChar() defined as returning a pointer to char when it does no such thing?

pow() is a float function, not an int function. It is a bit like using an elephant gun to swat mosquitoes, anyway.

You can not expect exact integer results.
Logged

Asnieres sur Seine - France
Offline Offline
Jr. Member
**
Karma: 0
Posts: 53
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Whoops. You're right PaulS I originally had returned the char as a pointer rather than passing the char as an argument. That didn't work as I wanted and when I put the char in as the argument I forgot to change the returning variable to void.

I do realise that pow() is a float (double) function. However I am unaware of any other function in Arduino which would allow me to return 10 to the power of X. Obviously I can replace it with a for loop multiplying 10 by itself X number of times. But that just seems a lot less elegant and less logical to me.

If I use pow(10,2), pow(10,4), pow(10,6), ... I always get full integer results even without doing an int(pow(10,2)), ...

However if I use pow(10,iDigs) I always get a "rounded down" result regardless of the value of iDigs.

Thanks.
Logged

New Jersey
Offline Offline
Faraday Member
**
Karma: 70
Posts: 3726
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Using pow with constants means that the compiler can pre-calculate it for you, presumably using non floating point math. Anything the arduino does with pow at runtime will be subject to rounding error.
Logged

Asnieres sur Seine - France
Offline Offline
Jr. Member
**
Karma: 0
Posts: 53
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks to the notes here I've replaced my pow(10,iDigs) call to a for loop as follows:

Code:
    // Separator = 10 to the power of number of decimal places
    long dSep = 10;
    for (int i = 1; i < iDigs; i++) {
      dSep *= 10;
    }

This allows me to safely pass the number of decimal places as an argument to the function.

Any other ideas?
Logged

California
Offline Offline
Faraday Member
**
Karma: 91
Posts: 3426
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Any other ideas?


You could make an ipow function:

Code:
int ipow(int base, int exp)
{
  int result = 1;
  for (int i=0; i<exp; i++)
  {
    result *= base;
  }
  return result;
}

Here's the solution to the floating point problem: http://www.hobbytent.com/viewtopic.php?f=1&t=158#p29

I wouldn't exactly call it a "problem", more of a "limitation". And that seems like an awful lot of work for something that can be done with a couple lines of code.
« Last Edit: February 11, 2013, 10:12:08 am by Arrch » Logged

Asnieres sur Seine - France
Offline Offline
Jr. Member
**
Karma: 0
Posts: 53
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

iPow()? Duh! I wish I thought of that!

Obviously that is the more elegant, and flexible, solution.

<sarcasm>
I hate you Arrch! I had put my code away for the day and you have made me go back to it!
</sarcasm>

Works perfectly. Thanks.
Logged

Worst state in America
Offline Offline
God Member
*****
Karma: 32
Posts: 808
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I wouldn't exactly call it a "problem", more of a "limitation". And that seems like an awful lot of work for something that can be done with a couple lines of code.

It's a big problem when someone wants to print a floating point number by doing it the standard way and ends up with a question mark.

Then they go over their code with a fine tooth comb, trying to find what's wrong.

Being unable to find anything wrong (because there isn't), they finally post here asking why it doesn't work.

And the problem is solved by simply checking "on" the "Enable floating point support" option in Preferences.

I fail to see how clicking a check box is "an awful lot of work"...

If anything is awful, it's using kludges of extra code to do what a simple "%f" would do.

Oh, yes I know. It would use a few extra bytes of flash and EVERYONE'S sketch is 32767 bytes long and they just can't spare any more.
Logged

Gentlemen may prefer Blondes, but Real Men prefer Redheads!

Offline Offline
Jr. Member
**
Karma: 0
Posts: 50
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I swapped to a Mega last month. Checking that box is fine by me.

I'd like to point out here that both serial land sdfat have .print and support floats. My original solution was to just use those to do what i wanted.
Logged

California
Offline Offline
Faraday Member
**
Karma: 91
Posts: 3426
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It's a big problem when someone wants to print a floating point number by doing it the standard way and ends up with a question mark.

So the effects create problems; that doesn't mean the cause is in itself, a problem. If I write a sketch that uses 3Kb SRAM and it doesn't work, I have a problem, but that doesn't make the memory limitation "the problem".

Quote
And the problem is solved by simply checking "on" the "Enable floating point support" option in Preferences.
I don't have that option in my Arduino IDE, so apparently, it's not that simple.

Quote
I fail to see how clicking a check box is "an awful lot of work"...

What happens when IDE changes break the "fix"? Where do I go to get the updated "fix"?

Quote
If anything is awful, it's using kludges of extra code to do what a simple "%f" would do.

Oh, yes I know. It would use a few extra bytes of flash and EVERYONE'S sketch is 32767 bytes long and they just can't spare any more.

Getting people to think about other ways to approach a problem and practice their problem solving skills through critical thinking is nothing to scoff at. Stuff like this also helps highlight the limitations of the hardware and encourages to think about it while they are writing their code.
« Last Edit: February 14, 2013, 12:32:15 am by Arrch » Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 50
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

What you said makes sense, except that limitation does not exist if they use up to date hardware. The mega came out ages ago then there was the mega 2560. Now we have the DUE.

Seeing as the overall goal of Arduino is to create prototype systems that may warrant actual development I don't see why the additional detail in data(i mean floating point data) availability should be limited.

%f is a lot more intuitive and usable then the horrible kludges I read. Isn't this meant to be an easy to use platform?
Logged

Pages: [1] 2 3   Go Up
Jump to: