Arduino String to Float: Find out how to do it Easily. Is there a simple
function that does this for you? How to convert strings to floats using c-style or C++ strings techniques.
Arduino String to Float: One common task when programming an Arduino is
converting string data received from the serial port into numeric values
that can be
used in calculations or comparisons.
This tutorial will explain how to
convert Arduino strings to floats - decimal numbers that allow for
fractional values.
Converting a string floating point number is not for the faint
hearted (floats are complicated) so the easiest way to do it is to use a
pre-defined function.
Arduino floating point numbers are usually represented using 32bits
when you use 8 bit processors; This is variable of type 'float' .
For example Uno and Nano use 32bits.
When you use a 32bit processor
you'll probably get 64 bits (this is type 'double'). In any case if you
use the type double, for an 8 bit Arduino it is automatically changed to
type float (32bit).
C++ Arduino String to float function
The simplest way to convert an Arduino string to a float when you use C++ Strings is to use the built-in stringToFloat() function. This takes a string as a parameter and returns the corresponding float value.
String input = "3.14";
float number;
number = stringToFloat(input);
In this C++ example, we start with a string "3.14" and assign it to
the input variable, then declare a float called number to hold the
output. The stringToFloat() function converts the string and stores the
result (3.14) in variable 'number'.
C-style Arduino String to float function
For C coding in Arduino, you can use the standard C library function
atof() to perform the same conversion. The function atof() stands for
ascii to float meaning "string to float" and works just like
stringToFloat() except it takes a char pointer rather than a String
object.
char input[] = "3.14";
float number;
number = atof(input);
This C example is nearly identical, but declares the input as a char
array rather than a String. It then uses atof() to convert the char
array to a float.
Handling Invalid Conversion
It's important to consider what happens if the string cannot be
converted to a valid float value. Both stringToFloat() and atof() will
return 0 in this case rather than producing an error. You may want to
add validation to check for this outcome.
By checking if the result is 0, this allows your code to handle
invalid conversions gracefully rather than having unexpected behavior
from bad input data.
Example Sketch - User Input with C++ strings
A common scenario is converting input from a the serial port
interface to a float. The following demonstrates getting a string from
Serial and validating the conversion.
String input;
float number;
if(Serial.available()>0){
input = Serial.readString();
number = stringToFloat(input);
if(number != 0){
// use converted number
} else {
// invalid input
}
}
By reading the string, converting, and checking for errors, this
allows safe conversion of dynamic user input to numeric values your
program can understand.
Example Sketch - c-style string input
For instance you might have a PID project that requires three
parameters kd, kp and ki. The following program parses the input string,
and assigns the value to each floating point variable
// Input buffer to hold all serial data
charinputBuffer[50];
// PID variables
float kp, ki, kd;
voidsetup(){
Serial.begin(115200);
}
voidloop(){
// Check for serial data
if(Serial.available() > 0){
// Get input string
Serial.readBytesUntil('\n', inputBuffer, 50);
char* token = strtok(inputBuffer, " ,");
while(token != NULL){
if(strcmp(token, "kp") == 0){
token = strtok(NULL, " ,");
kp = atof(token);
}
elseif(strcmp(token, "kd") == 0){
token = strtok(NULL, " ,");
kd = atof(token);
}
elseif(strcmp(token, "ki") == 0){
token = strtok(NULL, " ,");
ki = atof(token);
}
token = strtok(NULL, " ,");
}
// Output values
Serial.print("kp: "); Serial.println(kp,3);
Serial.print("kd: "); Serial.println(kd,3);
Serial.print("ki: "); Serial.println(ki,3);
}
}
Entering the string "kp 1.0, kd 2.0, ki 3.0" results in the output:
kp: 1.000
kd: 2.000
ki: 3.000
You can also enter only on parameter. For instance entering the string "kd 0.24" results in output:
kp: 1.000
kd: 0.240
ki: 3.000
Conclusions
This tutorial covered the essential basics of converting Arduino
strings
to floats using either stringToFloat() or atof(). Being able to read
text string inputs to and convert them to numeric values allows you to
get floating point values into your project code without re-compiling it
each
time!
Written by John Main, who has a degree in Electronic Engineering.
A PIR sensor lets your Arduino sense movement without contact. This tutorial covers PIR sensor basics, connecting one to an Arduino board and coding a motion detector.
Arduino Hall Effect Sensor: Add magnetic sensing superpowers to your Arduino projects with an easy-to-use hall effect sensor. With full code and layout...
Get started with an Arduino humidity sensor using the DHT11, which reports both humidity and temperature. Complete guide with full code for using this sensor
Comments
Have your say about what you just read! Leave me a comment in the box below.
Don’t see the comments box? Log in to your Facebook account, give Facebook consent, then return to this page and refresh it.