Moving a servo to a position on certain time

Hello,

First of all thanks for reading my post. I’m trying to make a servo move to a given angle in a given time. I’m using a SG90 servo (it has a speed of 0.10 seg/60° at 4.8V) with an Arduino Uno. I have the following ideas for code:

#include <Servo.h>

Servo servoMotor;
int posF = 180; //final position
int posA = 0; //initial position
long tF = 5; //desired time
long tA = 0; //actual time
int tDelay = 5; //time for the delay

void setup() {
  Serial.begin(9600);
  servoMotor.attach(9);
  tF = tF * 1000; //Just to convert time in ms
  servoMotor.write(posA); //Initialize the servo in 0
  //Serial.println("Pos   Tie");
}

void loop() {
  if (posA != posF && tA =< tF) {
    mueveServo();
  }
}

void mueveServo() {
  servoMotor.write(posA);
  posA = posA + 1; //Updates position
  delay(tDelay);
  tA = millis() + tDelay; //Updates time
  //Serial.print(posA); Serial.print("      "); Serial.println(tA);
}

I know that the sum of the delays and the running time must be equal to the desired time, but due to the speed of the servo it finishes before the time. Any ideas on how to modify the code to control the speed so the servo reaches the angles in the given time?

Here’s my solution:

#include <Servo.h>

Servo servoMotor;
int posF = 90;
int posA = 0;
long tF = 10;
long tA = 0;
int tDelay = 0;

void setup() {
  Serial.begin(9600);
  servoMotor.attach(9);
  tF = tF * 1000;
  tDelay = tF/posF;
  servoMotor.write(posA);
}

void loop() {
  if (posA != posF && tA <= tF) {
    mueveServo();
  }
}

void mueveServo() {
  servoMotor.write(posA);
  posA = posA + 1;
  delay(tDelay);
  tA = tA + tDelay;
  Serial.print(posA); Serial.print("   "); Serial.println(tA);
}

You know that never reaches the finish? You move the stepper to a new position, then you advance your position. If it reaches the finish then it doesn't move the servo again, so the servo is left sitting at the position just before the finish.

Shouldn't you be calculating tdelay as (total time for the move)/(number of movements required to get there)?

Steve

ordaz13:
I know that the sum of the delays and the running time must be equal to the desired time, but due to the speed of the servo it finishes before the time.

If you use millis() to manage your timing it will automatically take account of the time in other activities. Have a look at how it is done in the demo Several Things at a Time.

The demo also includes code to move a servo in small increments.

You have not told us how precise your timing needs to be? is an error of 100 millisecs OK?

...R