Setting position of servo motor
0-9 works fine, sets position in 20 degree increments
I want to set at 4.5 which is 90 degrees
when I send 4.5 from the serial monitor I get
Moving servo to 80.00°
Moving servo to 100.00°
sets at 4 then 5, not 4.5
I used float to define variables so 4.5 should be 90 degrees
what am I missing here?
do not understand this line
pulsewidth=(myangle*9)+500;//convert angle to 500-2480 pulse width
//servo motor control test
int servopin=9;//select D9 for servomotor signal line
float myangle;//initialize angle variable
float pulsewidth;//initialize width variable
float val;
void servopulse(int servopin,float myangle)//define servo pulse function
{
pulsewidth=(myangle*9)+500;//convert angle to 500-2480 pulse width
digitalWrite(servopin,HIGH);//set D9 on
delayMicroseconds(pulsewidth);//delay microseconds of pulse width
digitalWrite(servopin,LOW);//set D9 off
delay(20-pulsewidth/1000);
}
void setup()
{
pinMode(servopin,OUTPUT);//set D9 as output
Serial.begin(38400);//connect serial port, set baud rate 9600
Serial.println("Servo is ready");
}
void loop() //convert numbers 0-9 to corresponding 0-180 degree angle,LED blinks corresponding number of times
{
val=Serial.read();//read value of serial port
if(val>='0'&&val<='9')
{
val=val-'0';//convert quantity to numerical variable
val=val*(20);//convert val to angle
Serial.print("Moving servo to ");
Serial.print(val);
Serial.print("\xC2\xB0");
Serial.println();
for(int i=0;i<=50;i++)//give servo time to rotate to angle
{
servopulse(servopin,val);//use pulse function
}
}
}
Apparently the serial monitor sends a single ASCII character at a time. So 4.5 sent from serial monitor is seen by IDE as: numeral 4, not a number, numeral 5.
"modified code from "Ultimate Starter Kit with Mega 2560 for Arduino" PDF lesson 24:servo motor control test" is the original source of this code before I modified it
...does not answer the question "Why do you think you need a floating point value?"
"modified code from "Ultimate Starter Kit with Mega 2560 for Arduino" PDF lesson 24:servo motor control test" is the original source of this code before I modified it
Hey! Guess what? Not everyone is in possession of that particular .pdf.
Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.
The parse example includes how to deal with a floating point value.