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?