1

Is anyone aware of an Arduino library for smoothly controlling a servo?

I have an especially fast servo, which is trivial to control using Arduino's built-in Servo library. However, the library doesn't support proportional control. You specify a position, and the servo immediately goes to that position as fast as it can. With my servo, that creates incredibly fast jerky motion.

I've found some algorithms for interpolating a smooth servo motion by generating small incremental changes to the signal over time. I've been able to translate this to some Arduino code, and although the motion is much slower, it's still very jittery.

I've search for pure Arduino implementations, but I've not found anything. Does anyone know of an implementation? I find it hard to believe no one else has faced this type of servo control problem with an Arduino before.

3 Answers 3

5

Infortunately, I did not find any library but I found that the method shown below could work quite well for small projects. By adding a small delay, it helps the servo run a little smoother. It is not really ideal but it should work if your goal is to minimize the roughness of the servo.

Also by adding a 100uF capacitor between 5V and GND, the capacitor will help calm the sudden rush you might get when the servo first starts to turn. That rush is caused by the servo asking for more current when the servo is not moving.

#include <Servo.h>   //servo library
Servo myservo;       //servo object
int previousAngle = 0;

const int potPin = A3; //sensor pin

void setup() {
  myservo.attach(9);  //data pin of the servo
  pinMode(potPin, INPUT); //sensor pin as an input
}

void loop() {
  int val = analogRead(potPin);
  int angle = map(val, 0, 1023, 0, 180);

  if(angle>previousAngle)
  {
    for(int i=previousAngle; i<=angle; i++)
    {
      myservo.write(i); //turn servo by 1 degrees
      delay(10);        //delay for smoothness
    }
  }

  if(angle<previousAngle)
  {
    for(int i=previousAngle; i>=angle; i--)
    {
      myservo.write(i); //turn servo by 1 degrees
      delay(10);        //delay for smoothness
    }
  }

  previousAngle = angle;
}
1
  • I think this code should work with an else if. I made a thread myself, where I will make a 4 servo code for a robotic arm, working right, giving credit to you for the original code of course. Still you get +1 for this and the capacitor suggestion.
    – George Eco
    Commented May 14, 2021 at 8:02
5

After searching via a different angle (using "easing" as a keyword), I found this excellent library. Apparently this task is more commonly known as "servo easing", not smoothing. I've tested it with a hobby servo, and it does exactly what I was looking for.

1

Searching the net for smooth servo movement I found this entry one year ago.

In the end I built a new library for this task called ServoEasing.

Not the answer you're looking for? Browse other questions tagged or ask your own question.