how to convert string coming from serial port to float num

hi, i'm trying to send data through serial port, the data is float number
what i just planning for is to convert these data coming from the serial port to float in order to apply mathematical and logical manipulation inside the arduino
for example when i send 1 i just want to return 1 and 500 return 500 in one line and defined as float
i tried to use this code which i found here but it gives me an error
the code for the arduino is

int val;
void setup() {
  
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  while(Serial.available() == 0 );
  val = Serial.read();
  Serial.println(val);
  char carray[val.length()+1];
  val.toCharArray(carray,sizeof(val));
  int n = atoi(val);
  Serial.println(n);
  

}
Arduino: 1.6.1 (Windows 8.1), Board: "Arduino Uno"

serial.ino: In function 'void loop()':

serial.ino:14:19: error: request for member 'length' in 'val', which is of non-class type 'int'

serial.ino:15:7: error: request for member 'toCharArray' in 'val', which is of non-class type 'int'

serial.ino:15:19: error: 'carray' was not declared in this scope

serial.ino:16:19: error: invalid conversion from 'int' to 'const char*' [-fpermissive]

In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:23:0,

                 from serial.ino:1:

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stdlib.h:274:12: error:   initializing argument 1 of 'int atoi(const char*)' [-fpermissive]

 extern int atoi(const char *__s) __ATTR_PURE__;

            ^

Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

any help will be appreciated

You try to use functions of the String class on a value of type int.

Serial.read reads only one characters, and removes it from the input buffer.

Store each of these characters in a char arrays, and then use function atof to convert the string into a float.

Alternatively, you can use Serial.parseFloat().

and then use function atof to convert the string into a float.

Sorry I'm tired.. :slight_smile:

  while(Serial.available() == 0 );
  val = Serial.read();

Why not wait until 4 bytes come in, then read/convert at one time?

if (Serial.available()>3){
// read/process bytes

If don't have 4, keep on doing other stuff.

The examples in serial input basics include a parse example that includes reading a float value.

...R