Datasheet
Using feedback in your code
Now that we have a calibrated feedback signal, we can easily convert between servo position
and feedback voltages in our code.
Seeking to a position
The following bit of code will seek to a position and return as soon as we reach it. There is no
need to add an arbitrary delay to the code because the feedback signal will tell us exactly when
we get there!
int maxFeedback;
int tolerance = 2; // max feedback measurement error
/*
This function establishes the feedback values for 2 positions of the servo.
With this information, we can interpolate feedback values for intermediate positions
*/
void calibrate(Servo servo, int analogPin, int minPos, int maxPos)
{
// Move to the minimum position and record the feedback value
servo.write(minPos);
minDegrees = minPos;
delay(2000); // make sure it has time to get there and settle
minFeedback = analogRead(analogPin);
// Move to the maximum position and record the feedback value
servo.write(maxPos);
maxDegrees = maxPos;
delay(2000); // make sure it has time to get there and settle
maxFeedback = analogRead(analogPin);
}
void setup()
{
myservo.attach(servoPin);
calibrate(myservo, feedbackPin, 20, 160); // calibrate for the 20-160 degree range
}
void loop()
{
}
void Seek(Servo servo, int analogPin, int pos)
{
// Start the move...
servo.write(pos);
// Calculate the target feedback value for the final position
int target = map(pos, minDegrees, maxDegrees, minFeedback, maxFeedback);
// Wait until it reaches the target
while(abs(analogRead(analogPin) - target) > tolerance){} // wait...
© Adafruit Industries http://learn.adafruit.com/analog-feedback-servos Page 8 of 12