reading a number from the serial port and assign to a variable

i am sending some text to the serial port "Speed99.9%"

i want to put the 99.9 into a variable that is a float

I have some code

 while (Serial.available()) 
    InChr=;  //gets one byte from serial buffer
    if (InChr == '%') 
    }  //breaks out of capture loop to print readstring
    InStr += InChr ; 
 if (InStr == 'Reset') 
       N = 0 ;
       InStr = '' ;
  if (InStr.substring(0,5) == 'Speed') 
    InStr = InStr.substring(5) ;
    TargetSpeed =  float(InStr); //////////// ERROR HERE
    Serial.print("Speed Mode ON - ") ;
    Serial.println(TargetSpeed) ;

is there a simple way to convert a string into a float ?

You could convert your String to a char string and use "atof"

i tried

InChr = char(InStr.substring(5))

when i compiled i get - invalid cast from type 'String' to type 'char'


I wrote "convert", not "cast". Have a look at the documentation for the String class on how to convert to a char string.

Unfortunately, the String object is not a char array - which is what atof() needs (Ascii To Float) - atof() is the closest function to what you want to do (casting it with (float) won't work - they are too dissimilar).

You can convert it to a char 'string' with the toCharArray() function, like this:

String InStr="99.99";
char buff[32]="";
buff[ sizeof(buff) / sizeof(buff[0]) - 1 ]='\0'; // I always like to null terminate strings just in case
TargetSpeed =  atof(buff);

Thanks David, that worked a treat

Gadget999: Thanks David, that worked a treat

Glad to help - there's a shorter way to do this if the value is an int, using a String member function, but I can't find the listing where I heard of it - nonetheless, I think this is the easiest way to manage floats...