Servo rotate and return

Hello all,

I’m trying to write a generic function to rotate a servo from a starting point to a finishing point and then back to the starting point.

So far I have the code below (the ReadServo and MoveServo are simple functions that just use Servo.read() and Servo.write):

int ServoForwardBack(Servo servoToFlick, int rotateTo) {
  // Get current position
  int startPosition = ReadServo(servoToFlick);

  // Check if rotation is out of scale
  if(rotateTo >= 0 && rotateTo <= 180) {
    MoveServo(servoToFlick, rotateTo);
    while(ReadServo(servoToFlick) != rotateTo) {
      continue;
    }
    
    MoveServo(servoToFlick, startPosition);
    return 1;
    
  } else {
    return 0;
  }
}

The problem is, the servo gets set to the finish point and then back to the start point far quicker than it can actually move, so it doesn’t actually do anything.

I don’t want to use the delay function as this is for a generic servo, and all servos will rotate at different speeds.

How do I solve this problem?

(oh just as a side question, I’m looking to also have a motor that can rotate forwards and backwards, I think I need some sort of motor control board, but I can’t quite remember. What is it I search for to start looking into that?)

Thanks in advance!

'm looking to also have a motor that can rotate forwards and backwards,

It is called an H-bridge motor driver.

The VarSpeedServo library might be of interest.

Do you know that Servo.read() does not return the actual physical position of the servo, but the last position that your software sent to the servo?

groundFungus:
It is called an H-bridge motor driver.

The VarSpeedServo library might be of interest.

Do you know that Servo.read() does not return the actual physical position of the servo, but the last position that your software sent to the servo?

Thanks, that library looks good but I'm getting nothing but errors.....

EDIT: Solved, you can't have the VarSpeedServo and the Servo libraries in the same sketch.

    MoveServo(servoToFlick, rotateTo);
    while(ReadServo(servoToFlick) != rotateTo) {
      continue;
    }

It all makes sense when you read the documentation for Servo.read(). It can’t sense the position of the servo so it just returns the last value sent with Servo.write(). Your wait loop ends immediately. Perhaps using a tiny delay and moving a degree at a time would produce the effect you want. See File->Examples->Servo->Sweep