arduinoarduino-unoservo

Servo Speed Control


How can i make my servo do this but slower?

if(angle == 140)

angle = 159;

else

if(angle == 159)

angle = 140;

This is the whole code:

    #include <Servo.h>

const int TOUCH_SENSOR_PIN   = 6;   // Arduino pin connected to touch sensor's pin
const int TOUCH_SENSOR_PIN2   = 7 ;
const int SERVO_PIN          = 9;   // Arduino pin connected to servo motor's pin

Servo servo; // create servo object to control a servo

// variables will change:
int angle = 140;           // the current angle of servo motor
int lastTouchState;      // the previous state of touch sensor
int currentTouchState;   // the current state of touch sensor
int lastTouchState2;      // the previous state of touch sensor 2
int currentTouchState2;   // the current state of touch sensor 2


void setup() {
  Serial.begin(9600);      // initialize serial
  pinMode(TOUCH_SENSOR_PIN, INPUT);
  pinMode(TOUCH_SENSOR_PIN2, INPUT);
  servo.attach(SERVO_PIN);       // attaches the servo on pin 9 to the servo object

  servo.write(angle);
  currentTouchState = digitalRead(TOUCH_SENSOR_PIN);
  currentTouchState2 = digitalRead(TOUCH_SENSOR_PIN2);
}

void loop() {
  lastTouchState    = currentTouchState;  // save the last state
  currentTouchState = digitalRead(TOUCH_SENSOR_PIN);  //read new state 
  
  lastTouchState2    = currentTouchState2;  // save the last state
  currentTouchState2 = digitalRead(TOUCH_SENSOR_PIN2);  //read new state 

  if((lastTouchState == LOW && currentTouchState == HIGH) || (lastTouchState2 == LOW && currentTouchState2 == HIGH)) {

    if(angle == 140)
      angle = 159;
    else
    if(angle == 159)
      angle = 140;


    // control servo motor arccoding to the angle
    servo.write(angle);
    

  }  }

Solution

  • you can control the speed of the servo by making it rotating several little steps instead of giving it the final demand angle, something like this.

      if(angle <= 140){
        for (; angle<= 150; angle += 1) {
          myservo.write(angle);
          delay(15);
        }
      }
      else if(angle >= 150){
        for (; angle >= 140; angle -= 1) {
          myservo.write(angle);
          delay(15);
        }
      }
    
    

    you can adjust the speed by changing the delay value in both for-loops. A full working example can be found in the examples provided by the Arduino IDE under Servo -> Sweep I guess.