Pages: [1] 2   Go Down
Author Topic: dtostrf() alternative for concatenating a float and a string  (Read 25943 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 6
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm trying to concatenate a string and a floating point number to send to the serial monitor and the only way I can find to do it is using dtostrf(), but that seems a little clumsy.
For example (this works):
Code:
  int potValue = analogRead(pinSensor);
  float volts = 5*(float)potValue/1023;
  String strLab = "Pot Voltage = ";
  char tmp[10];
  dtostrf(volts,1,2,tmp);
  String strOut = strLab + tmp;

  Serial.println(strOut);

This doesn't work:
Code:
  int potValue = analogRead(pinSensor);
  float volts = 5*(float)potValue/1023;
  char tmp[10];
  dtostrf(volts,1,2,tmp);

  Serial.println("Pot Voltage = " + tmp);
 
  BlinkLED(pinLED,potValue,potValue);
nor does:
Code:
  int potValue = analogRead(pinSensor);
  float volts = 5*(float)potValue/1023;
  char tmp[10];
  dtostrf(volts,1,2,tmp);
  String strOut = "Pot Voltage = " + tmp;

  Serial.println(strOut);
both give the error:  invalid operands of types 'const char [15]' and 'char [10]' to binary 'operator+'

What I'd really like to do is somthing like:
Code:
  int potValue = analogRead(pinSensor);
  float volts = 5*(float)potValue/1023;

  Serial.println("Pot Voltage = " + String(Volts));
but String doesn't work with floating point numbers. 

I've looked at the String constructor tutorial, the String Addition Examples and googled this as well to no avail.  Any suggestions?
Thanks,
Jason
Logged

California
Online Online
Faraday Member
**
Karma: 92
Posts: 3446
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Any suggestions?
Use null terminated character arrays instead of Strings and use sprintf to "concatenate"
Logged

New Hampshire
Offline Offline
God Member
*****
Karma: 17
Posts: 781
There are 10 kinds of people, those who know binary, and those who don't.
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
char voltageMsg[25];
sprintf(voltageMsg, "Pot Voltage = %f", volts);
Serial.println(voltageMsg);
Logged


Global Moderator
Netherlands
Online Online
Shannon Member
*****
Karma: 227
Posts: 14013
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

try this,
Code:
int potValue = analogRead(pinSensor);
float volts = 5*(float)potValue/1023;

char tmp[25] = "Pot Voltage = ";

dtostrf(volts,1,2, &tmp[12]);

Serial.println(tmp);

The char array is declared big enough to hold the fixed string and the float.  (25)
The whole trick is to let the dtostrf add to the tmp array at the right position. (you might need to change 12 in 13 or so)

give it a try.


Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 651
Posts: 50845
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
use sprintf to "concatenate"
Great idea, except that sprintf() on the Arduino does not deal with floating point values.

OP: Why do you feel it is necessary to concatenate the data before sending it?
Code:
Serial.print("Pot Voltage = ");
Serial.print(volts);
The device on the other end of the serial port will not know that two Serial calls were made to send the data.
Logged

Global Moderator
Netherlands
Online Online
Shannon Member
*****
Karma: 227
Posts: 14013
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


Quote
The device on the other end of the serial port will not know that two Serial calls were made to send the data.
For Serial you are 100% right. however if you use the print on a TCP socket, multiple calls might cause fragmentation of IP packets.
Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

California
Online Online
Faraday Member
**
Karma: 92
Posts: 3446
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
use sprintf to "concatenate"
Great idea, except that sprintf() on the Arduino does not deal with floating point values.
Didn't realize that, thanks.
Logged

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

try this,
Code:
int potValue = analogRead(pinSensor);
float volts = 5*(float)potValue/1023;

char tmp[25] = "Pot Voltage = ";

dtostrf(volts,1,2, &tmp[12]);

Serial.println(tmp);

The char array is declared big enough to hold the fixed string and the float.  (25)
The whole trick is to let the dtostrf add to the tmp array at the right position. (you might need to change 12 in 13 or so)

give it a try.




I'll give this a shot--I wonder if it'd be possible to write a wrapper function for dtostrf so that you could just use it in-line. 
Is there a reason that adding the string literal and variable (see my first post for code) doesn't work?  seems like it should from the string constructor tutorial.
Logged

Global Moderator
Netherlands
Online Online
Shannon Member
*****
Karma: 227
Posts: 14013
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


String strOut = "Pot Voltage = " + tmp;

does not work as the addition of two char[] is not defined..

String strOut = String("Pot Voltage = ") + String(tmp); 

might work. String("not tried");  smiley-wink


Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Global Moderator
Melbourne, Australia
Offline Offline
Brattain Member
*****
Karma: 511
Posts: 19306
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm trying to concatenate a string and a floating point number to send to the serial monitor  ...

... however if you use the print on a TCP socket ...

Which, fortunately, we don't have to worry about. smiley
Logged

http://www.gammon.com.au/electronics

Please post technical questions on the forum - not to me by personal message. Thanks a lot.

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

Dear,

I tried all the tips posted above, but none of them worked for me. I put my code below to see if anyone has a suggestion. The problem just seems damn 'float'. Since I can not turn it into string, it does not work my insertion into the database using the library mysql.h.


Code:
#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

// Network conf.
byte mac_addr[] = { 0x54, 0x55, 0x4F, 0x11, 0x0F, 0x2C };
EthernetClient client;
//Server address
IPAddress server_addr(1, 1, 1, 1);

//Data variables
int pinosensor = 0;
int valorlido = 0;
float temperatura = 0;
int porta = 8;

//Configuracao da conexao com o arduino
Connector my_conn; // The Connector/Arduino reference

char user[] = "arduino";
char password[] = "arduino";

void read_dados(){
  pinMode(porta, INPUT);
  //Medidor de Temperatura
  valorlido = analogRead(pinosensor);
  temperatura = (valorlido * 0.00488);
  temperatura = temperatura * 100;
  Serial.print("Temperatura atual: ");
  Serial.println(temperatura);
  Serial.print("\n");
}

char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
  char fmt[20];
  sprintf(fmt, "%%%d.%df", width, prec);
  sprintf(sout, fmt, val);
  return sout;
}

void insert_data(){
 
  //Don't work - this is a test from toppic 103935.0
  String strLab = "Temperatura = ";
  char tmp[10];
  dtostrf(temperatura,1,2,tmp);
  String strOut = strLab + tmp;
  Serial.println(strOut);
  //the result of this serial.println is Temperatura = ?
  
  //Don't work - this is a test from toppic 103935.0
  char voltageMsg[25];
  sprintf(voltageMsg, "Temperatura : %f", temperatura);
  Serial.println(voltageMsg);
  //the result of this serial.println is Temperatura : ?

    
  //Just function 'now()' is inputed correctly in Database
  char buf[256];
  sprintf(buf, "INSERT INTO datacenter.tb_teste (data, temp) VALUES (now(), %d)", temperatura);
  my_conn.cmd_query(buf);

}

void setup() {
  
  // start the serial library:
  Serial.begin(9600);
  // start the Ethernet connection:
  if (Ethernet.begin(mac_addr) == 0) {
    Serial.println("DHCP Failed");
    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }
  
  // print your local IP address:
  Serial.println(Ethernet.localIP());
  delay(1000);
  //database connection
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)){
  delay(500);
      Serial.println("Connected!");
    }else{
      Serial.println("Connection failed!");
    }
      
}

void loop() {
  
 read_dados();
 insert_data();
 delay(10000);
  
}//end
« Last Edit: August 01, 2013, 02:44:17 pm by rafanun » Logged

Global Moderator
Netherlands
Online Online
Shannon Member
*****
Karma: 227
Posts: 14013
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

please use code tags when you post code - it is the # button above the smileys - You can modify your post, select the code part and press #

Thank you,
Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Atlanta, USA
Offline Offline
Edison Member
*
Karma: 56
Posts: 1847
AKA: Ray Burne
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Or,

Use streaming, Example:

Code:
Serial << "Answer: " << _FLOAT(sqrt(a*a + b*b), decimals);


http://playground.arduino.cc/Main/StreamingOutput
« Last Edit: July 31, 2013, 11:00:00 am by mrburnette » Logged

Global Moderator
Melbourne, Australia
Offline Offline
Brattain Member
*****
Karma: 511
Posts: 19306
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

There's a FormatDouble library:

http://forum.arduino.cc/index.php/topic,148214.0.html
Logged

http://www.gammon.com.au/electronics

Please post technical questions on the forum - not to me by personal message. Thanks a lot.

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

I'm having a issue, I'm getting data from a sensor that is in double format. I thought I could format it into String and post it on the LCD.

Code:
#include <FormatDouble.h>

dTemp=fmtDouble(dTTempF, 6, buf, sizeof buf);

1. I thought LCD's could display Strings or Chars (guess menu system (MenWiz) or LCD doesn't like inputs)
2. Does anyone know how to convert a double to a char?

MenWiz doesn't play nice with Sprintf.....to make this more difficult!
« Last Edit: January 04, 2014, 10:23:10 pm by JAnwyl » Logged

Pages: [1] 2   Go Up
Jump to: