Advertisement
TolentinoCotesta

Servo smoothmove

Jul 20th, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <Servo.h>  
  2.  
  3. class myServo : public Servo {  
  4.   public:  
  5.     uint16_t MINPULSE = 980;      // durata impulso minima
  6.     uint16_t MAXPULSE = 2020;     // durata impulso massima
  7.     float speed_constant = 0.03F; // servo factor, the higher the faster
  8.     void smoothmove(int setPosition) ;
  9. };
  10.  
  11. // servo_smoothmove by witpim. 2007
  12. void myServo::smoothmove(int setPosition) {
  13.  static int oldPosition;
  14.  int anglediff = abs(setPosition - oldPosition);
  15.  float speed_factor = speed_constant/anglediff;
  16.  static int oldposition;
  17.  for (float timeAngle=0.000; timeAngle<=1;) {
  18.    timeAngle = timeAngle + speed_factor;
  19.    float timeAngleadjust = (1.0/2.0) - (1.0/2.0*cos(timeAngle*PI));
  20.    float moveAngle = (anglediff*timeAngleadjust);
  21.    int calc_angle;
  22.    if (oldPosition > setPosition)
  23.      calc_angle =  oldPosition - (int)moveAngle;
  24.    else
  25.      calc_angle =  oldposition + (int)moveAngle ;
  26.    // Uso writeMicroseconds perché cosi posso adeguare il software al reale comportamento del servo
  27.    this->writeMicroseconds(map(calc_angle, 0, 180, MINPULSE, MAXPULSE));
  28.  }
  29.  oldPosition = setPosition;
  30. }
  31.  
  32. myServo Servo1, Servo2;
  33.  
  34. void setup() {
  35.    Serial.begin(9600);
  36.    Servo1.attach(9);
  37.    Servo2.attach(10);
  38.    Servo2.speed_constant = 0.05F;
  39. }
  40.  
  41. void loop() {
  42.  Servo1.smoothmove(0);
  43.  Servo1.smoothmove(180);
  44.  Servo2.smoothmove(0);
  45.  Servo2.smoothmove(180);
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement