How to send int & float to serial with multi digits?

I want to send two variables over serial as :

int var1 = 10;
float var2 =  15.2;

so string must be as : 0010 0015.2

The C-string functions itoa() and dtostf() will do the job.

sprintf() does not support float variables on many Arduinos.

Does dtostf do leading zeroes?

The traditional Arduino way to insert leading zeroes (typically used for month, day, minute, and second):

  if (number < 1000)
    Serial.print('0');
  if (number < 100)
    Serial.print('0');
  if (number < 10)
    Serial.print('0');
  Serial.print(number);
1 Like

first want to add int & float to a string then will send over http & serial
but is there a way to set precision of float variable to 1 or 2 after decimal point?

dtostrf()

void setup()
{
  Serial.begin(115200);
  fdevopen (putChar, getChar); // See https://forum.arduino.cc/t/easy-way-of-doing-printf/369075/20
  printf("0x%04X %02d:%02d:%02d.%06d\n",-1,1,2,3,micros());
}

void loop()
{
}

// See https://forum.arduino.cc/t/easy-way-of-doing-printf/369075
int getChar (FILE *fp)
{
    while (!(Serial.available()));
    return (Serial.read());
}

int putChar (char c, FILE *fp)
{
    if (c == '\n') {
        putChar ((char) '\r', fp);
    }
    Serial.write (c);
    return 0;
}

0xFFFF 01:02:03.000028

result is as 0001.20

how to make result as 0001.2?

Serial.print(number,1);

1 Like

it is ok for serial,
but how about put result in a string as 1 decimal point?

Many classes like Client inherit from the Stream class (as do are the "Serial" classes). So, the class you'll use to "send over http" might just have the capability built in (just like "Serial").

With dtostrf(), use "1" for the argument that specifies the number of decimal places.

the result after adding zeros as a string 0001.20 so the question is how to make result as 0001.2
note: I have multi values so want to put inside a string then send over mqtt or http

Change:
Serial.print(number);
to
Serial.print(number, 1);

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.