Change servo speed?

@timtiernan,

you can try like this example:


const int ROTATION_DELAY = 25; // Play wiht this number, 25ms looks smooth and was quiet on my servo

struct MyServo{
  byte rgbColor[3];
  int target;
  int actual;
  unsigned long lastUpdateMillis;
  Servo* servo;
  int pin;
  // not used here //void begin(int pin) {servo = new Servo; pinMode(pin, OUTPUT); servo->attach(pin); servo->write(actual);} ;
  void begin(int pin, byte r, byte g, byte b) {this->servo = new Servo; pinMode(pin, OUTPUT); servo->attach(pin); servo->write(actual); rgbColor[0] = r; rgbColor[1] = g; rgbColor[2] = b; } ;
};

//Tim's Two MyServo objects:
MyServo timServo;
MyServo louServo;

void updateServo(MyServo& servo);

void setup()
{
  Serial.begin(9600);
  Particle.function("timservo", setTimServo);
  Particle.function("louservo", setLouServo);
  Particle.variable("timPos", timServo.actual);
  Particle.variable("louPos", louServo.actual);
  // begin() initializes the servos and sets them to position zero... don't use this method outside of setup()
  timServo.begin(D0, 0, 0, 255); // (PIN for Servo, RED, GREEN, BLUE) values RGB LED
  louServo.begin(D1, 0, 255, 0);
}

void loop()
{
  updateServo(timServo);
  updateServo(louServo);
}

void updateServo(MyServo& servo)
{
  if(servo.target == servo.actual)
  {
    return;
  }
  unsigned long nowMillis = millis();
  if(nowMillis - servo.lastUpdateMillis > ROTATION_DELAY)
  {
    RGB.control(true);
    RGB.color(servo.rgbColor[0], servo.rgbColor[1], servo.rgbColor[2]);
    Serial.printlnf("Actual:%03d, Target:%03d", servo.actual, servo.target);
    if(servo.actual < servo.target) servo.actual++;
    else servo.actual--;
    servo.servo->write(servo.actual);
    servo.lastUpdateMillis = nowMillis;
    if(servo.actual == servo.target) RGB.control(false);
  }
}

int setTimServo(String command)
{
  uint8_t timpos = command.toInt();
  if(timpos >= 0 and timpos <= 180)  // you may have to adjust if (like me) you don't get a full 180 degrees of rotation on your servos
  {
    timServo.target = timpos;
    return timpos;
  }
  return -1;
}

int setLouServo(String command)
{
  uint8_t loupos = command.toInt();
  if(loupos >= 0 and loupos <= 180)
  {
    louServo.target = loupos;
    return loupos;
  }
  return -1;
}
2 Likes