Using serial value to control a servo

I have a project to control a servo using an AFR gauge kit as a sensor that communicates to Arduino by serial. I upload this code to Arduino to check what the AFR sends to Arduino.

#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial (5, 6);
Servo myservo;

int val;

void setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);
  myservo.attach(10);
}

void loop() 
{
  if(mySerial.available())
  {
    Serial.write(mySerial.read());
  }
  
  if(Serial.available())
  {
    mySerial.write(Serial.read());
  }
}

Then, I open the serial monitor to check the value. It shows the value that ranges from 0.0 to 99.9. I tested the servo to be controlled by the value from the serial, but the servo moved randomly. I changed the code to check if the serial sends the exact value or only the characters.

#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial (5, 6);
Servo myservo;

int val;

void setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);
  myservo.attach(10);
}

void loop() 
{
  if(mySerial.available())
  {
    Serial.write(mySerial.read());
    Serial.write('\n');
  }
  
  if(Serial.available())
  {
    mySerial.write(Serial.read());
    mySerial.write('\n');
  }
}

I open the serial monitor, and it shows something like the image below, and I conclude that the servo can’t move properly because the serial only sends the character.

So, how to convert the characters sent from the serial into integer/float value?

how to convert the characters sent from the serial into integer/float value?

Use Serial.parseFloat() to read the value, but note that servo.write() takes an integer as its parameter and you may also need to use the map() function to change the range of values received into a range of 0to 180 to position your servo

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

…R