Go Down

Topic: dtostrf() alternative for concatenating a float and a string (Read 26 times) previous topic - next topic

StrikeEagleIII

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: [Select]

  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: [Select]

  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: [Select]

  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: [Select]

  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

Arrch


Any suggestions?

Use null terminated character arrays instead of Strings and use sprintf to "concatenate"

jraskell

Code: [Select]

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

robtillaart

try this,
Code: [Select]

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.


Rob Tillaart

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

PaulS

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: [Select]
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.

robtillaart


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.
Rob Tillaart

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

Arrch


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.

StrikeEagleIII


try this,
Code: [Select]

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.

robtillaart


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


Rob Tillaart

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

Nick Gammon


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. :)
http://www.gammon.com.au/electronics

rafanun

#10
Jul 31, 2013, 02:39 pm Last Edit: Aug 01, 2013, 09:44 pm by rafanun Reason: 1
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: [Select]

#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

robtillaart

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,
Rob Tillaart

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

mrburnette

#12
Jul 31, 2013, 05:51 pm Last Edit: Jul 31, 2013, 06:00 pm by mrburnette Reason: 1
Or,

Use streaming, Example:

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


http://playground.arduino.cc/Main/StreamingOutput

Nick Gammon

There's a FormatDouble library:

http://forum.arduino.cc/index.php/topic,148214.0.html
http://www.gammon.com.au/electronics

JAnwyl

#14
Jan 05, 2014, 03:26 am Last Edit: Jan 05, 2014, 04:23 am by JAnwyl Reason: 1
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: [Select]

#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!

Go Up